python_多进程_Pool


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,并传给各个子进程:
     =  Queue()
     =  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()
     =  manager.Queue()
     =  Pool()
     pw  =  p.apply_async(write, args = (q,))
     pr  =  p.apply_async(read, args = (q,))
     p.close()
     p.join()
     print ( '====================================' )
     print ( '所有数据都写入并且读完' )
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值