python 簡單的生產者和消費者模型

# !/usr/bin/env Python3
# -*- coding: utf-8 -*-
# @Author   : zsc
# @FILE     : 簡單的隊列的生產者和消費者.py
# @Time     : 2020/7/6 16:42
# @Software : PyCharm


import time
import queue
import threading


q = queue.Queue(10)  # 生成一個隊列,用來保存“包子”,最大數量爲10


# 生產者
def productor(i):
    # 廚師不停地每2s做一個包子
    while True:
        print(i)
        q.put("廚師%s做的包子!" % i)
        time.sleep(2)


def consumer(i):
    # 顧客不停地每1s喫一個包子
    while True:
        print("顧客%s吃了一個%s" % (i, q.get()))
        time.sleep(1)


# 實例化3個生產者(廚師)
for i in range(3):
    t = threading.Thread(target=productor, args=(i,))
    t.start()

# 實例化10個消費者
for j in range(10):
    v = threading.Thread(target=consumer, args=(j,))
    v.start()

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章