队列在线程编程时特别有用,因为信息必须在多个线程之间安全地交换。
队列作用:
1、解耦;
2、提高运行效率。
import queue
常用方法:
queue.Queue(maxsize=0) #先入先出
queue.LifoQueue(maxsize=0) #Lifo: last in fisrt out,表示后进先出
queue.PriorityQueue(maxsize=0) #存储数据时可设置优先级的队列,注意这里存数据要用元组的形式,eg:
q = queue.PriorityQueue() q.put((1,'aa'))
q.qsize() # 返回队列中的元素数量
q.empty() # 判断队列是否为空,为空时返回True
q.full() # 判断队列是否已满,已满时返回True
q.put(item, block=True, timeout=None) # 向队列中传入元素
注意:此处传入元素值的时候若包含变量,只能使用%s或%d这种方式传入,不能使用“+”或“,”。
q.put_nowait(item) # 无需等待传入元素(当队列已满时使用put方法传入元素会卡住等待队列释放空间,调用put_nowait方法则直接打印异常queue.Full)
Queue.get(block=True, timeout=None) # 移出/获取队列元素
Queue.get_nowait() # 无需等待移出元素(当队列为空时使用get方法获取不到元素会卡住等待元素传入队列,调用get_nowait方法则直接打印异常queue.Empty)
代码饭粒1:简单的生产者消费者模型
import threading, queue def producer(): for i in range(10): q.put("food %s" % i) print("begin get food...") q.join() # 等待队列被取空后再继续执行后面代码 print("no food to get...") def consumer(n): while q.qsize() > 0: print("%s get" % n, q.get()) q.task_done() # 告知这个任务执行完了 q = queue.Queue() p = threading.Thread(target=producer, ) p.start() c1 = consumer("gay")
代码饭粒2:生产者消费者模型2
import threading,queue,time q = queue.Queue(maxsize=10) def Produce(name): count = 1 while True: print("[%s] total produce %s food." % (name,count)) q.put("food%d" % count) count += 1 time.sleep(2) def Consumer(name): # while not q.empty(): # 不能用上述判断方式的原因是供不应求时,会发生阻塞 while True: print("[%s] get [%s] and eating..." % (name,q.get())) time.sleep(1) p = threading.Thread(target=Produce,args=('fone',)) p2 = threading.Thread(target=Produce,args=('zff',)) c = threading.Thread(target=Consumer,args=('chaiquan',)) c2 = threading.Thread(target=Consumer,args=('jumao',)) p.start() p2.start() c.start() c2.start()
代码饭粒3:生产者消费者模型3
import time,random import queue,threading q = queue.Queue() def Producer(name): count = 0 while count < 20: time.sleep(random.randrange(3)) q.put(count) print('Producer %s has produced %s baozi..' %(name, count)) count +=1 def Consumer(name): count = 0 while count < 20: time.sleep(random.randrange(4)) if not q.empty(): data = q.get() print(data) print('\033[32;1mConsumer %s has eat %s baozi...\033[0m' %(name, data)) else: print("-----no baozi anymore----") count += 1 p1 = threading.Thread(target=Producer, args=('A',)) c1 = threading.Thread(target=Consumer, args=('B',)) p1.start() c1.start()
posted on
浙公网安备 33010602011771号