用python生成器实现单线程并发(做包子和吃包子)追加一种多线程队列实现并发

#第一种方法:单线程单过程,要等包子全部做好之后才能一个一个的吃
import time
def produce_baozi():
    res=[]
    for i in range(1,21):
        time.sleep(0.2)
        res.append("包子%s"%i)
    return res
def consume_baozi(x):
    for index,baozi in enumerate(x):
        time.sleep(0.1)
        print("第%s个人吃了%s"%(index+1,baozi))
ret=produce_baozi()
consume_baozi(ret)

#第二种方法:单线程并发,包子边做边吃
import time
def produce_baozi():
    global i
    for i in range(1,21):
        time.sleep(1)
        yield i
        print("第%s个包子做好了"%i)
        consume_baozi()
def consume_baozi():
    global i
    time.sleep(1)
    print("第%s个人吃了第%s个包子"%(i,i))
res=produce_baozi()
while True:
    try:
       res.__next__()
    except StopIteration:
        break

多线程队列实现并发
生产者一共生产12个包子,三个消费者没人吃4个,边做边吃

import time
import threading         #线程模块
import queue             #队列模块
q=queue.Queue(10)        #创建一个队列对象,允许放10个数据,不限类型
# print("bug")
def produce_baozi(name):
    for i in range(1,13):
        time.sleep(1)
        print("%s的第%s个包子做好了" % (name,i))
        q.put(i)
        q.task_done()     #线程间通信
def consume_baozi(name):
    for i in range(1, 5):
        q.join()          #如果通信线程没有执行q.task_done(),该线程则会阻塞
        date=q.get()
        time.sleep(1)
        print("%s吃了第%s个包子"%(name,date))
p1=threading.Thread(target=produce_baozi,args=("p1",))
c2=threading.Thread(target=consume_baozi,args=("c2",))
c3=threading.Thread(target=consume_baozi,args=("c3",))
c1=threading.Thread(target=consume_baozi,args=("c1",))
c1.start()
c2.start()
c3.start()
p1.start()
c1.join()
c2.join()
c3.join()
p1.join()
print("end...")

你可能感兴趣的:(python,开发之路)