python执行多进程时,如何获取函数返回的值
发布网友
发布时间:2022-04-26 22:15
我来回答
共2个回答
热心网友
时间:2022-04-18 06:03
共享变量的方法。
没有办法直接实现你的需求,但是,你可以用共享变量的方法实现,比如:
def worker(procnum, return_dict):
'''worker function'''
print str(procnum) + ' represent!'
return_dict[procnum] = procnumif __name__ == '__main__':
manager = Manager()
return_dict = manager.dict()
jobs = [] for i in range(5):
p = multiprocessing.Process(target=worker, args=(i,return_dict))
jobs.append(p)
p.start() for proc in jobs:
proc.join() print return_dict.values()
热心网友
时间:2022-04-18 07:21
交换数据一般用queue吧。
17.2.1.3. Exchanging objects between processes
multiprocessing supports two types of communication
channel between processes:
Queues
The Queue
class is a near clone of queue.Queue. For example:
from multiprocessing import Process, Queue
def f(q):
q.put([42, None, 'hello'])
if __name__ == '__main__':
q = Queue()
p = Process(target=f, args=(q,))
p.start()
print(q.get()) # prints "[42, None, 'hello']"
p.join()
Queues are thread and process safe.
Pipes
The Pipe() function returns a pair of connection objects
connected by a pipe which by default is plex (two-way). For example:
from multiprocessing import Process, Pipe
def f(conn):
conn.send([42, None, 'hello'])
conn.close()
if __name__ == '__main__':
parent_conn, child_conn = Pipe()
p = Process(target=f, args=(child_conn,))
p.start()
print(parent_conn.recv()) # prints "[42, None, 'hello']"
p.join()
The two connection objects returned by Pipe()
represent the two ends of the pipe. Each connection object has send()
and recv()
methods (among others). Note that data in a pipe may become corrupted if two
processes (or threads) try to read from or write to the same end of the
pipe at the same time. Of course there is no risk of corruption from processes
using different ends of the pipe at the same time.