Skip to end of metadata
1.apply/apply_async方法,每次只能向进程池分配一个任务,那如果想一次分配多个任务到进程池中,可以使用map/map_async方法。首先来看下map_async方法是如何定义的:
apply/apply_async使用循环创建,
map/map_async太复杂,不建议使用,需要计算参数列表的个数https://www.cnblogs.com/Tour/p/4564710.html
2.当直接通过pool+queue进行多进程操作,程序不会响应,队列对象不能在父进程与子进程间通信,如果想要使用进程池中使用队列则要使用multiprocess的Manager类
备注:网上有人这样操作会有报错提示:RuntimeError: Queue objects should only be shared between processes through inheritance
#本来我想要的是将会得到一个队列,将其作为参数传入进程池子里的每个子进程 #直接pool+queue,程序无响应,pw,pr直接没有响应 #网上有人这样操作会有报错提示:RuntimeError: Queue objects should only be shared between processes through inheritance
from
multiprocessing
import
Process, Queue,Pool,Manager
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,并传给各个子进程:
# 父进程创建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
(
'所有数据都写入并且读完'
)
|
#进程池中使用队列则要使用multiprocess的Manager类,用Manage的实例去定义queue,程序运行结果与预期一致
if
__name__
=
=
'__main__'
:
# 父进程创建Queue,并传给各个子进程:
# 父进程创建Queue,并传给各个子进程:
manager
=
Manager()
q
=
manager.Queue()
p
=
Pool()
pw
=
p.apply_async(write, args
=
(q,))
pr
=
p.apply_async(read, args
=
(q,))
p.close()
p.join()
print
(
'===================================='
)
print
(
'所有数据都写入并且读完'
)
|