11.python并发入门(part8 基于线程队列实现生产者消费者模型)
一、什么是生產者消費者模型?
生產者就是生產數據的線程,消費者指的就是消費數據的線程。
在多線程開發過程中,生產者的速度比消費者的速度快,那么生產者就必須等待消費者把數據處理完,生產者才會產生新的數據,相對的,如果消費者處理數據的速度大于生產者,那么消費者就必須等待生產者。
為了解決這種問題,就有了生產者消費者模型。
生產者與消費者模型,是通過一個容器,來解決生產者和消費者之間的耦合性問題,生產者和消費者之間并不會直接通信,這樣生產者就無需等待消費者處理完數據,生產者可以直接把數據扔給隊列,這個時候消費者也無需找生產者要數據,直接去隊列中取數據,這個隊列,起到的就是一個緩沖區的作用,具有平衡生產者和消費者的處理能力。
二、基于隊列的生產者消費者模型的示例。
ver1:
#!/usr/local/bin/python2.7
# -*- coding:utf-8 -*-
import time
import random
import Queue
import threading
q1 = Queue.Queue()
def producer(name):
? ? count = 0
? ? while count < 10:
? ? ? ? print ?"making..."
? ? ? ? time.sleep(random.randrange(3))
? ? ? ? q1.put(count)
? ? ? ? print "procucer %s has produced %s baozi...." %(name,count)
? ? ? ? count += 1
? ? ? ? print "ok!"
def consumer(name):
? ? count = 0
? ? while count < 10:
? ? ? ? time.sleep(random.randrange(4))
? ? ? ? if not q1.empty():
? ? ? ? ? ? data = q1.get()
? ? ? ? ? ? print data
? ? ? ? ? ? print '\033[32;1mConsumer %s has eat %s baozi...\033[0m' %(name, data)
? ? ? ? else:
? ? ? ? ? ? print "not fond baozi"
? ? ? ? count += 1
if __name__ == '__main__':
? ? p1 = threading.Thread(target=producer,args=('A',))
? ? c1 = threading.Thread(target=consumer,args=('B',))
? ? p1.start()
? ? c1.start()
ver2:
#!/usr/local/bin/python2.7
# -*- coding:utf-8 -*-
import time
import random
import Queue
import threading
q1 = Queue.Queue()
def producer(name):
? ? count = 0
? ? while count < 10:
? ? ? ? print ?"making..."
? ? ? ? time.sleep(random.randrange(3))
? ? ? ? q1.put(count)
? ? ? ? print "procucer %s has produced %s baozi...." %(name,count)
? ? ? ? count += 1
? ? ? ? q1.task_done() ?#給隊列發個信號,告訴隊列put完畢
? ? ? ? #q1.join()
? ? ? ? print "ok!"
def consumer(name):
? ? count = 0
? ? while count < 10:
? ? ? ? q1.join() ##監聽生產者發送給隊列的信號
? ? ? ? time.sleep(random.randrange(4))
? ? ? ?# if not q1.empty():
? ? ? ? data = q1.get()
? ? ? ? #q1.task_done()
? ? ? ? print data
? ? ? ? print '\033[32;1mConsumer %s has eat %s baozi...\033[0m' %(name, data)
? ? ? ? #else:
? ? ? ? #print "not fond baozi"
? ? ? ? count += 1
if __name__ == '__main__':
? ? p1 = threading.Thread(target=producer,args=('A',))
? ? c1 = threading.Thread(target=consumer,args=('B',))
? ? c2 = threading.Thread(target=consumer,args=('C',))
? ? c3 = threading.Thread(target=consumer,args=('D',))
? ? p1.start()
? ? c1.start()
? ? c2.start()
? ? c3.start()
轉載于:https://blog.51cto.com/suhaozhi/1925548
總結
以上是生活随笔為你收集整理的11.python并发入门(part8 基于线程队列实现生产者消费者模型)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: javaweb 中的过滤器 包装器
- 下一篇: Spring提取@Transaction