Python多線程的簡單實現(生產者消費者模型)


 1 __author__ = "JentZhang"
 2 
 3 import time, threading, queue
 4 
 5 q = queue.Queue(maxsize=10)  # 聲明隊列
 6 
 7 
 8 def Producer(name):
 9     '''生產者'''
10     count = 1
11     while True:
12         q.put(count)  # 往隊列中添加數據
13         print("[%s] 生產了第%s包子\n" % (name, count))
14         count += 1
15         time.sleep(3)
16 
17 
18 def Consumer(name):
19     '''消費者'''
20     while True:
21         i = q.get()  # 從隊列中取數據
22         print("====[%s] 吃了第%s個包子\n" % (name, i))
23         time.sleep(1)
24 
25 
26 '''設置多線程'''
27 p = threading.Thread(target=Producer, args=("Jent",))
28 c1 = threading.Thread(target=Consumer, args=("張三",))
29 c2 = threading.Thread(target=Consumer, args=("李四",))
30 
31 '''線程開啟'''
32 p.start()
33 c1.start()
34 c2.start()

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM