本文转载
Python Queue模块详解
Python中,队列是线程间最常用的交换数据的形式。Queue模块是提供队列操作的模块,虽然简单易用,但是不小心的话,还是会出现一些意外。
创建一个“队列”对象
import Queue
q = Queue.Queue(maxsize = 10)
Queue.Queue类即是一个队列的同步实现。队列长度可为无限或者有限。可通过Queue的构造函数的可选参数maxsize来设定队列长度。如果maxsize小于1就表示队列长度无限。
将一个值放入队列中
q.put(10)
调用队列对象的put()方法在队尾插入一个项目。put()有两个参数,第一个item为必需的,为插入项目的值;第二个block为可选参数,默认为
1。如果队列当前为空且block为1,put()方法就使调用线程暂停,直到空出一个数据单元。如果block为0,put方法将引发Full异常。
将一个值从队列中取出
q.get()
调用队列对象的get()方法从队头删除并返回一个项目。可选参数为block,默认为True。如果队列为空且block为True,get()就使调用线程暂停,直至有项目可用。如果队列为空且block为False,队列将引发Empty异常。
Python Queue模块有三种队列及构造函数:
1、Python Queue模块的FIFO队列先进先出。 class Queue.Queue(maxsize)
2、LIFO类似于堆,即先进后出。 class Queue.LifoQueue(maxsize)
3、还有一种是优先级队列级别越低越先出来。 class Queue.PriorityQueue(maxsize)
此包中的常用方法(q = Queue.Queue()):
q.qsize() 返回队列的大小
q.empty() 如果队列为空,返回True,反之False
q.full() 如果队列满了,返回True,反之False
q.full 与 maxsize 大小对应
q.get([block[, timeout]]) 获取队列,timeout等待时间
q.get_nowait() 相当q.get(False)
非阻塞 q.put(item) 写入队列,timeout等待时间
q.put_nowait(item) 相当q.put(item, False)
q.task_done() 在完成一项工作之后,q.task_done() 函数向任务已经完成的队列发送一个信号
q.join() 实际上意味着等到队列为空,再执行别的操作
范例:
实现一个线程不断生成一个随机数到一个队列中(考虑使用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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
|
#!/usr/bin/env python
#coding:utf8
import
random,threading,time
from
Queue
import
Queue
#Producer thread
class
Producer(threading.Thread):
def
__init__(
self
, t_name, queue):
threading.Thread.__init__(
self
,name
=
t_name)
self
.data
=
queue
def
run(
self
):
for
i
in
range
(
10
):
#随机产生10个数字 ,可以修改为任意大小
randomnum
=
random.randint(
1
,
99
)
print
"%s: %s is producing %d to the queue!"
%
(time.ctime(),
self
.getName(), randomnum)
self
.data.put(randomnum)
#将数据依次存入队列
time.sleep(
1
)
print
"%s: %s finished!"
%
(time.ctime(),
self
.getName())
#Consumer thread
class
Consumer_even(threading.Thread):
def
__init__(
self
,t_name,queue):
threading.Thread.__init__(
self
,name
=
t_name)
self
.data
=
queue
def
run(
self
):
while
1
:
try
:
val_even
=
self
.data.get(
1
,
5
)
#get(self, block=True, timeout=None) ,1就是阻塞等待,5是超时5秒
if
val_even
%
2
=
=
0
:
print
"%s: %s is consuming. %d in the queue is consumed!"
%
(time.ctime(),
self
.getName(),val_even)
time.sleep(
2
)
else
:
self
.data.put(val_even)
time.sleep(
2
)
except
:
#等待输入,超过5秒 就报异常
print
"%s: %s finished!"
%
(time.ctime(),
self
.getName())
break
class
Consumer_odd(threading.Thread):
def
__init__(
self
,t_name,queue):
threading.Thread.__init__(
self
, name
=
t_name)
self
.data
=
queue
def
run(
self
):
while
1
:
try
:
val_odd
=
self
.data.get(
1
,
5
)
if
val_odd
%
2
!
=
0
:
print
"%s: %s is consuming. %d in the queue is consumed!"
%
(time.ctime(),
self
.getName(), val_odd)
time.sleep(
2
)
else
:
self
.data.put(val_odd)
time.sleep(
2
)
except
:
print
"%s: %s finished!"
%
(time.ctime(),
self
.getName())
break
#Main thread
def
main():
queue
=
Queue()
producer
=
Producer(
'Pro.'
, queue)
consumer_even
=
Consumer_even(
'Con_even.'
, queue)
consumer_odd
=
Consumer_odd(
'Con_odd.'
,queue)
producer.start()
consumer_even.start()
consumer_odd.start()
producer.join()
consumer_even.join()
consumer_odd.join()
print
'All threads terminate!'
if
__name__
=
=
'__main__'
:
main()
|
本文转载
作者:Kevin_Yang
链接:http://my.oschina.net/yangyanxing/blog/296052
python中的Queue与多进程(multiprocessing)
最近接触一个项目,要在多个虚拟机中运行任务,参考别人之前项目的代码,采用了多进程来处理,于是上网查了查python中的多进程
一、先说说Queue(队列对象)
Queue是python中的标准库,可以直接import 引用,之前学习的时候有听过著名的“先吃先拉”与“后吃先吐”,其实就是这里说的队列,队列的构造的时候可以定义它的容量,别吃撑了,吃多了,就会报错,构造的时候不写或者写个小于1的数则表示无限多
import Queue
q = Queue.Queue(10)
向队列中放值(put)
q.put(‘yang’)
q.put(4)
q.put([‘yan’,’xing’])
在队列中取值get()
默认的队列是先进先出的
>>> q.get()
'yang'
>>> q.get()
4
>>> q.get()
['yan', 'xing']
>>>
当一个队列为空的时候如果再用get取则会堵塞,所以取队列的时候一般是用到
get_nowait()方法,这种方法在向一个空队列取值的时候会抛一个Empty异常
所以更常用的方法是先判断一个队列是否为空,如果不为空则取值
队列中常用的方法
Queue.qsize() 返回队列的大小
Queue.empty() 如果队列为空,返回True,反之False
Queue.full() 如果队列满了,返回True,反之False
Queue.get([block[, timeout]]) 获取队列,timeout等待时间
Queue.get_nowait() 相当Queue.get(False)
非阻塞 Queue.put(item) 写入队列,timeout等待时间
Queue.put_nowait(item) 相当Queue.put(item, False)
二、multiprocessing中使用子进程概念
from multiprocessing import Process
可以通过Process来构造一个子进程
p = Process(target=fun,args=(args))
再通过p.start()来启动子进程
再通过p.join()方法来使得子进程运行结束后再执行父进程
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
from
multiprocessing
import
Process
import
os
# 子进程要执行的代码
def
run_proc(name):
print
'Run child process %s (%s)...'
%
(name, os.getpid())
if
__name__
=
=
'__main__'
:
print
'Parent process %s.'
%
os.getpid()
p
=
Process(target
=
run_proc, args
=
(
'test'
,))
print
'Process will start.'
p.start()
p.join()
print
'Process end.'
|
三、在multiprocessing中使用pool
如果需要多个子进程时可以考虑使用进程池(pool)来管理
from multiprocessing import Pool
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
from
multiprocessing
import
Pool
import
os, time
def
long_time_task(name):
print
'Run task %s (%s)...'
%
(name, os.getpid())
start
=
time.time()
time.sleep(
3
)
end
=
time.time()
print
'Task %s runs %0.2f seconds.'
%
(name, (end
-
start))
if
__name__
=
=
'__main__'
:
print
'Parent process %s.'
%
os.getpid()
p
=
Pool()
for
i
in
range
(
5
):
p.apply_async(long_time_task, args
=
(i,))
print
'Waiting for all subprocesses done...'
p.close()
p.join()
print
'All subprocesses done.'
|
pool创建子进程的方法与Process不同,是通过
p.apply_async(func,args=(args))实现,一个池子里能同时运行的任务是取决你电脑的cpu数量,如我的电脑现在是有4个cpu,那会子进程task0,task1,task2,task3可以同时启动,task4则在之前的一个某个进程结束后才开始
上面的程序运行后的结果其实是按照上图中1,2,3分开进行的,先打印1,3秒后打印2,再3秒后打印3
代码中的p.close()是关掉进程池子,是不再向里面添加进程了,对Pool对象调用join()方法会等待所有子进程执行完毕,调用join()之前必须先调用close(),调用close()之后就不能继续添加新的Process了。
当时也可以是实例pool的时候给它定义一个进程的多少
如果上面的代码中p=Pool(5)那么所有的子进程就可以同时进行
三、多个子进程间的通信
多个子进程间的通信就要采用第一步中说到的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
|
#coding:gbk
from
multiprocessing
import
Process, Queue
import
os, time, random
# 写数据进程执行的代码:
def
write(q):
for
value
in
[
'A'
,
'B'
,
'C'
]:
print
'Put %s to queue...'
%
value
q.put(value)
time.sleep(random.random())
# 读数据进程执行的代码:
def
read(q):
while
True
:
if
not
q.empty():
value
=
q.get(
True
)
print
'Get %s from queue.'
%
value
time.sleep(random.random())
else
:
break
if
__name__
=
=
'__main__'
:
# 父进程创建Queue,并传给各个子进程:
q
=
Queue()
pw
=
Process(target
=
write, args
=
(q,))
pr
=
Process(target
=
read, args
=
(q,))
# 启动子进程pw,写入:
pw.start()
# 等待pw结束:
pw.join()
# 启动子进程pr,读取:
pr.start()
pr.join()
# pr进程里是死循环,无法等待其结束,只能强行终止:
print
print
'所有数据都写入并且读完'
|
四、关于上面代码的几个有趣的问题
|
1
2
3
4
5
6
7
8
9
10
11
|
if
__name__
=
=
'__main__'
:
# 父进程创建Queue,并传给各个子进程:
q
=
Queue()
p
=
Pool()
pw
=
p.apply_async(write,args
=
(q,))
pr
=
p.apply_async(read,args
=
(q,))
p.close()
p.join()
print
print
'所有数据都写入并且读完'
|
如果main函数写成上面的样本,本来我想要的是将会得到一个队列,将其作为参数传入进程池子里的每个子进程,但是却得到
RuntimeError: Queue objects should only be shared between processes through inheritance
的错误,查了下,大意是队列对象不能在父进程与子进程间通信,这个如果想要使用进程池中使用队列则要使用multiprocess的Manager类
|
1
2
3
4
5
6
7
8
9
10
11
12
13
|
if
__name__
=
=
'__main__'
:
manager
=
multiprocessing.Manager()
# 父进程创建Queue,并传给各个子进程:
q
=
manager.Queue()
p
=
Pool()
pw
=
p.apply_async(write,args
=
(q,))
time.sleep(
0.5
)
pr
=
p.apply_async(read,args
=
(q,))
p.close()
p.join()
print
print
'所有数据都写入并且读完'
|
这样这个队列对象就可以在父进程与子进程间通信,不用池则不需要Manager,以后再扩展multiprocess中的Manager类吧
关于锁的应用,在不同程序间如果有同时对同一个队列操作的时候,为了避免错误,可以在某个函数操作队列的时候给它加把锁,这样在同一个时间内则只能有一个子进程对队列进行操作,锁也要在manager对象中的锁
|
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
|
#coding:gbk
from
multiprocessing
import
Process,Queue,Pool
import
multiprocessing
import
os, time, random
# 写数据进程执行的代码:
def
write(q,lock):
lock.acquire()
#加上锁
for
value
in
[
'A'
,
'B'
,
'C'
]:
print
'Put %s to queue...'
%
value
q.put(value)
lock.release()
#释放锁
# 读数据进程执行的代码:
def
read(q):
while
True
:
if
not
q.empty():
value
=
q.get(
False
)
print
'Get %s from queue.'
%
value
time.sleep(random.random())
else
:
break
if
__name__
=
=
'__main__'
:
manager
=
multiprocessing.Manager()
# 父进程创建Queue,并传给各个子进程:
q
=
manager.Queue()
lock
=
manager.Lock()
#初始化一把锁
p
=
Pool()
pw
=
p.apply_async(write,args
=
(q,lock))
pr
=
p.apply_async(read,args
=
(q,))
p.close()
p.join()
print
print
'所有数据都写入并且读完'
|
参考文章:
http://blog.youkuaiyun.com/yatere/article/details/6668006
本文深入解析Python中的Queue模块,包括创建队列、数据进出队列的操作,以及如何在多进程环境下利用队列进行数据交互。通过实例展示了如何实现线程生成随机数、从队列中取出奇数和偶数等应用。


3123

被折叠的 条评论
为什么被折叠?



