python 生产者消费者模式

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

消费者执行完了所有任务


请使用浏览器的分享功能分享到微信等