python模块-queue

概述

上次简单总结了python的多线程模块,这次主要学习一下python的queue模块,仔细通读下来,有两点

  1. 在queue模块中,如果你要执行put的操作的时候,如果是多线程,就会比较难办,因为这个时候数据是无序的,机器也没办法知道哪个已经放进去了,哪个还没放进去,会变得混乱
  2. 如果是把它拿出来执行,那就很方便,因为这个是在一个队列里面。

下面我们总结一下概念

queue

queue实现了三种队列

  1. FIFO: 先进先出
  2. LIFO:后进先出
  3. 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
#!/usr/bin/env python
#-*- coding:utf-8 -*-
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) # do some work
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()

# 阻塞队列,直到所有任务都完成了,在开始加入None
q.join()

# 加入None,以便完成任务
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

#!/usr/bin/env python
#-*- coding:utf-8 -*-
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()
#if item is None:
#print("线程 {} 发现了一个None, 可以休息了. time:{}".format(i,ctime()))
#break
sleep(2) # do some work
print("线程{}将任务<{}>给完成了。time : {}".format(i,item,ctime()))
q.task_done()

def producer():
for i in range(10):
#sleep(0.5)
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)

#0:00:02.008000

总结

理解了多线程+queue,下一篇进行实战!

reference

https://www.t00ls.net/articles-44516.html

http://www.liujiangblog.com/course/python/59