猿问

如下,但执行的时候并没有返回任何参数

p=Pool(20)
with open(temp_path,'r') as f:
for line in f.readlines():
p.apply_async(execute_monitor_sql,args=(type,)) --其中execute_monitor_sql函数会返回一个执行结果。我需要将这些结果汇总到一个参数
p.close()
p.join()

白衣非少年
浏览 118回答 2
2回答

喵喔喔

共享变量的方法。没有办法直接实现你的需求,但是,你可以用共享变量的方法实现,比如: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()

qq_遁去的一_1

交换数据一般用queue吧。17.2.1.3. Exchanging objects between processesmultiprocessing supports two types of communicationchannel between processes:QueuesThe Queueclass is a near clone of queue.Queue. For example:from multiprocessing import Process, Queuedef 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.PipesThe Pipe() function returns a pair of connection objectsconnected by a pipe which by default is duplex (two-way). For example:from multiprocessing import Process, Pipedef 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 twoprocesses (or threads) try to read from or write to the same end of thepipe at the same time. Of course there is no risk of corruption from processesusing different ends of the pipe at the same time.
随时随地看视频慕课网APP

相关分类

Python
我要回答