概述
上次简单总结了python的多线程模块,这次主要学习一下python的queue模块,仔细通读下来,有两点
- 在queue模块中,如果你要执行put的操作的时候,如果是多线程,就会比较难办,因为这个时候数据是无序的,机器也没办法知道哪个已经放进去了,哪个还没放进去,会变得混乱
- 如果是把它拿出来执行,那就很方便,因为这个是在一个队列里面。
下面我们总结一下概念
queue
queue实现了三种队列
- FIFO: 先进先出
- LIFO:后进先出
- priority queue:优先值低的先出去,优先值相同的,先进先出
下面通过代码来学习一下队列多线程
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
|
from time import ctime,sleep import threading import queue
q = queue.Queue()
def work(i): while True: item = q.get() if item is None: print("线程 {} 发现了一个None, 可以休息了. time:{}".format(i,ctime())) break sleep(0.5) print("线程{}将任务<{}>给完成了。time : {}".format(i,item,ctime())) q.task_done()
def producer(): for i in range(10): sleep(0.5) q.put(i)
producer()
work_threads = []
for i in range(3): work_threads.append(threading.Thread(target=work,args=(i,)))
for t in work_threads: t.start()
q.join()
for i in range(10): q.put(None)
for t in work_threads: t.join()
|
另一种比较简单的写法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
|
from time import ctime,sleep import threading import queue from datetime import datetime q = queue.Queue()
def work(i): while not q.empty(): item = q.get() sleep(2) print("线程{}将任务<{}>给完成了。time : {}".format(i,item,ctime())) q.task_done()
def producer(): for i in range(10): q.put(i)
start = datetime.now() producer() work_threads = [threading.Thread(target=work,args=(i,)) for i in range(10)]
for t in work_threads: t.start()
for t in work_threads: t.join() end = datetime.now()
print(end-start)
|
总结
理解了多线程+queue,下一篇进行实战!
reference
https://www.t00ls.net/articles-44516.html
http://www.liujiangblog.com/course/python/59