ITPub博客

首页 > IT职业 > IT生活 > python 生产者消费者模式

python 生产者消费者模式

IT生活 作者:专注的阿熊 时间:2021-09-06 17:24:20 0 删除 编辑

import threading

import queue

import time

# 定义一个生产者

def producer():

     count = 0

     # 判断队列中任务的数量

     while q.qsize()<5:

         print(' 第 %s 顿饭 ......',count)

         q.put(count)

         count+=1

         time.sleep(1)

# 定义一个消费者

def consumer(name):

     while True:

         print("%s 吃了第 %s 饭 " % (name,q.get()))

# 定义一个队列

q = queue.Queue(maxsize=4)

t1 = threading.Thread(target=producer)

t2 = threading.Thread(target=consumer,args=('jibu',))

t1.start()

t2.start()

结果 :

第 %s 顿饭 ...... 0

jibu 吃了第 0 饭

第 %s 顿饭 ...... 1

jibu 吃了第 1 饭

第 %s 顿饭 ...... 2

jibu 吃了第 2 饭

第 %s 顿饭 ...... 3

jibu 吃了第 3 饭

第 %s 顿饭 ...... 4

jibu 吃了第 4 饭

第 %s 顿饭 ...... 5

jibu 吃了第 5 饭

第 %s 顿饭 ...... 6

jibu 吃了第 6 饭

第 %s 顿饭 ...... 7

jibu 吃了第 7 饭

第 %s 顿饭 ...... 8

# 另外,外汇跟单gendan5.com如果供大于求或者求大于供,可以在相对小的一方在增加线程的数量

当然如果需要进一步优化可以让消费者执行完队列中所有任务的时候告诉生产者一声

import threading

import queue

import time

# 定义一个生产者

def producer():

     count = 0

     # 判断队列中任务的数量

     for i in range(5):

         print(' 第 %s 顿饭 ......',count)

         q.put(count)

         count+=1

         time.sleep(1)

     q.join()

# 定义一个消费者

def consumer(name):

     while True:

         print("%s 吃了第 %s 饭 " % (name,q.get()))

         q.task_done()

         print(' 消费者执行完了所有任务 ')

# 定义一个队列

q = queue.Queue(maxsize=4)

t1 = threading.Thread(target=producer)

t2 = threading.Thread(target=consumer,args=('jibu',))

t1.start()

t2.start()

结果

第 0 顿饭 ......

jibu 吃了第 0 饭

消费者执行完了所有任务

第 1 顿饭 ......

jibu 吃了第 1 饭

消费者执行完了所有任务

第 2 顿饭 ......

jibu 吃了第 2 饭

消费者执行完了所有任务

第 3 顿饭 ......

jibu 吃了第 3 饭

消费者执行完了所有任务

第 4 顿饭 ......

jibu 吃了第 4 饭

消费者执行完了所有任务


来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/69946337/viewspace-2790651/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-08-23

  • 博文量
    410
  • 访问量
    276806