欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Python多线程的简单实现(生产者消费者模型)

程序员文章站 2023-08-26 15:24:51
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... ......
 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()