使用python进行多处理

时间:2010-10-03 12:58:51

标签: python multiprocessing

如何控制此函数池apply_asyn的返回值 假设我有以下很酷的

import multiprocessing:


de fun(..)
...
...
return value


my_pool = multiprocessing.Pool(2)


for i in range(5) :
    result=my_pool.apply_async(fun, [i])

 some code going to be here....

digest_pool.close()
digest_pool.join()
here i need to proccess the results 

如何控制每个进程的结果值,并知道检查它属于哪个进程,

3 个答案:

答案 0 :(得分:0)

从for循环中存储'i'的值,然后打印它或返回并将其保存在其他地方。 所以如果一个过程发生,你可以通过查看变量i来检查它是从哪个过程。

希望这有帮助。

答案 1 :(得分:0)

查看其他问题,它应该可以帮助您获取有关正在运行的线程的信息  How to find a thread id in Python

答案 2 :(得分:0)

您确定,您需要知道,您的两名工人中的哪一位现在在做什么?在这种情况下,您可能最好使用进程和队列,因为这听起来需要多个进程之间的某些通信。

如果您只想知道哪个结果由哪个工作人员处理,您只需返回一个元组:

#!/usr/bin/python
import multiprocessing

def fun(..)
...
    return value, multiprocessing.current_process()._name

my_pool = multiprocessing.Pool(2)
async_result = []

for i in range(5):
    async_result.append(my_pool.apply_async(fun, [i]))

# some code going to be here....

my_pool.join()
result = {}
for i in range(5):
    result[i] = async_result[i].get()

如果您将不同的输入变量作为列表,map_async命令可能是更好的决定:

#!/usr/bin/python
import multiprocessing

def fun(..)
...
...
    return value, multiprocessing.current_process()._name

my_pool = multiprocessing.Pool()

async_results = my_pool.map_async(fun, range(5))

# some code going to be here....

results = async_results.get()

最后一行加入游泳池。请注意,结果是元组列表,每个元组包含您计算的值以及计算它的进程的名称。