简单的并发生产者消费者模型 python
from Queue import Queue import random, threading, time class Producer(threading.Thread): def __init__(self, name, queue): threading.Thread.__init__(self, name=name) self.data = queue def run(self): for i in range(3): print("%s is producing %d to the queue!" % (self.getName(), i)) self.data.put(i) time.sleep(random.randrange(10) / 5) print("%s finished!" % self.getName()) class Consumer(threading.Thread): def __init__(self, name, queue): threading.Thread.__init__(self, name=name) self.data = queue def run(self): for i in range(3): print("%s is consuming %d to the queue!" % (self.getName(), i)) self.data.get() time.sleep(random.randrange(10) / 5) print("%s finished!" % self.getName()) def main(): queue = Queue() producer = Producer('Producer', queue) consumer = Consumer('Consumer', queue) producer.start() consumer.start() producer.join() consumer.join() print 'All threads finished!' if __name__ == '__main__': main()
重写run函数,引用队列 进行生产和消费 直接show code 。
another method
# -*- coding: utf-8 -*- from multiprocessing import Pool, Manager def product(queue): for i in range(3): queue.put('asdasdasd_{}'.format(i)) print 'product_{}'.format(i) def consumer(queue, i): queue.get_nowait() print '{}消费数据'.format(i) def main(): pool = Pool() queue = Manager().Queue() # 生产者生产数据 pool.apply_async(func=product, args=(queue,)) # 消费者消费数据 for i in range(3): pool.apply_async(func=consumer, args=(queue, i)) pool.apply_async(func=consumer, args=(queue, i)) pool.close() pool.join() print 'All threads finished!' if __name__ == '__main__': main()