from queue import Queue#先进先出队列
#创建队列
q=Queue(3)
print(q.empty())
#放数据:q.put()
q.put("d1")
q.put('d2')
q.put("d3")
print(q.full())
#取数据:q.get()
q.get()
q.get()
q.get()
print(q.empty())
#阻塞:同进程队列
#队列的优先级 from queue import PriorityQueue#优先级队列---继承了Queue pq=PriorityQueue() #任务不要直接put,需要封装到元组中 # 格式:(数字,消息),说明:数字越小,优先级越高 pq.put((1,"下载任务1")) pq.put((-1,"下载任务2")) pq.put((0,"下载任务3")) pq.put((100,"下载任务4")) # print(pq.get()) i=0 while i<pq.qsize(): print(pq.get())
#后进先出的队列 from queue import LifoQueue lq=LifoQueue() lq.put("d1") lq.put("d2") lq.put("d3") print(lq.get())#先拿d3
#生产者与消费者: from queue import Queue from threading import Thread import time q=Queue(maxsize=10) #生产者 def cooker(name): count=1 while True: q.put("包子%d"%count) print("%s--生产了包子%d"%(name,count)) count+=1 time.sleep(2) #消费者 def consemer(name): while True: print(name,"吃了%s"%q.get()) time.sleep(1) if __name__ == '__main__': #厨师1 c1=Thread(target=cooker,args=("刘大厨",)) c1.start() #厨师2 c2=Thread(target=cooker,args=("李大厨",)) c2.start() #消费者1 guke1=Thread(target=consemer,args=("小明",)) guke1.start() #消费者2 guke2=Thread(target=consemer,args=("狗蛋",)) guke2.start()
#增加全局变量和锁
from queue import Queue from threading import Thread,Lock import time q=Queue() lock=Lock() def cooker(name): global count while True: lock.acquire() q.put("包子%d"%count) print("%s--生产了包子%d"%(name,count)) count+=1 lock.release() time.sleep(1) def consemer(name): while True: print(name,"吃了",q.get()) time.sleep(1) if __name__ == '__main__': count = 1 c1=Thread(target=cooker,args=("刘大厨",)) c2=Thread(target=cooker,args=("李大厨",)) c1.start() c2.start() guke1=Thread(target=consemer,args=("张三",)) guke2=Thread(target=consemer,args=("李四",)) guke1.start() guke2.start()
#协程 import time def concumer(name): while True: baozi=yield print("%s吃了包子%d"%(name,baozi)) time.sleep(1) def producer(): r=con1.__next__() r=con2.__next__() n=1 while True: print("生产了两个包子") con1.send(n) con2.send(n+1) n+=2 if __name__ == '__main__': con1=concumer("张三") con2=concumer("李四") p=producer()
#递归 #用递归实现1--10的累加和 def dg(n): if n==1: return 1 return n+dg(n-1) if __name__ == '__main__': print(dg(10))