1. 程式人生 > 實用技巧 >生產者以及消費者模式(程序池)

生產者以及消費者模式(程序池)

code
import time
import random
from multiprocessing import Pool, Manager
 
# 生產者
def producer(q, i):
    food = 'Spam-%d' % i
    time.sleep(random.uniform(1, 2))
    timeVal = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    print('時間:%s\t生產者:%d\t生產了 Spam-%d' % (timeVal, i, i))
    q.put(food)
 
# 消費者
def consumer(q, i):
    
while True: food = q.get() if not food: break time.sleep(random.uniform(1, 2)) timeVal = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) print('時間:%s\t消費者: %d\t吃了 %s' % (timeVal, i, food)) if __name__ == '__main__': q = Manager().Queue() producterPool
= Pool(3) for n in range(1, 21): producterPool.apply_async(producer, (q, n)) consumerPoolNum = 5 consumerPool = Pool(consumerPoolNum) for n in range(1, consumerPoolNum + 1): consumerPool.apply_async(consumer, (q, n)) producterPool.close() producterPool.join()
for n in range(1, consumerPoolNum + 1): q.put(None) consumerPool.close() consumerPool.join() print('end')