Python随心记--线程列队
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python随心记--线程列队相关的知识,希望对你有一定的参考价值。
import threading,time li = [1,2,3,4,5,6] def pri(): while li: a = li[-1] print(a) time.sleep(1) li.remove(a) try: li.remove(a) except Exception as e: print(a,e) t1 = threading.Thread(target=pri,args=()) t1.start() t2 = threading.Thread(target=pri,args=()) t2.start()
先进先出
import queue #线程队列 2.7的时候q为大写 q = queue.Queue(3) #FIFO 默认 1先进先出 2先进后出 3后进先出 q.put(12) q.put(‘hello‘) q.put({‘name‘:‘aaron‘}) q.put(123,False) #如果已满就不再加进去 while 1: data = q.get() #data = q.get(block = False) print(data) print(‘------------------‘)
先进后出
import queue #线程队列 2.7的时候q为大写 q = queue.LifoQueue() #FIFO 默认 1先进先出 2先进后出 3后进先出 q.put(12) q.put(‘hello‘) q.put({‘name‘:‘aaron‘}) q.put(123,False) #如果已满就不再加进去 while 1: data = q.get() print(data) print(‘------------------‘) import queue #线程队列 2.7的时候q为大写 q = queue.LifoQueue() q.put(12) q.put(‘hello‘) q.put({‘name‘:‘aaron‘}) q.put(123,False) #如果已满就不再加进去 print(q.qsize()) print(q.empty()) print(q.full()) print(q.task_done()) #在完成任务之后q.task_done函数向任务已经完成的队列发送一个信号 print(q.join())
生成消费者模型:通过一个容器来解决生产者和消费者的强耦合问题
import queue,threading,time,random q = queue.Queue() def Producter(name): count = 0 while count < 10: print(‘making..............‘) time.sleep(random.randrange(3)) q.put(count) print(‘Producter %s has producter %s baozi。。‘ %(name,count)) count += 1 print(‘ok........‘) def Consumer(name): count = 0 while count < 10: time.sleep(random.randrange(4)) if not q.empty(): data = q.get() print(data) print(‘