我可以将方法传递给 apply_async 或映射到 python 多处理吗?
Can I pass a method to apply_async or map in python multiprocessing?
我怎样才能让下面的东西起作用?要点是我想 运行 一个异步的方法(而不是一个函数)。
from multiprocessing import Pool
class Async:
def __init__(self, pool):
self.pool = pool
self.run()
def run(self):
p.apply_async(self.f, (10, ))
def f(self, x):
print x*x
if __name__ == '__main__':
p = Pool(5)
a = Async(p)
p.close()
p.join()
这什么都不打印。
绝对可以在 python 中使用线程池对 class 方法进行线程处理 2 - 下面的程序达到了我的预期。
#!/usr/bin/env python
from multiprocessing.pool import ThreadPool
class TestAsync():
def __init__(self):
pool = ThreadPool(processes = 2)
async_completions = []
for a in range(2):
async_completions.append(pool.apply_async(self.print_int, ( a,)))
for completion in async_completions:
res = completion.get()
print("res = %d" % res)
def print_int(self, value):
print(value)
return (value*10)
a = TestAsync()
问题似乎是由于 multiprocessing
需要 pickle self.f
而绑定方法不可 pickle。有讨论如何解决问题here.
apply_async
显然创建了一个异常,该异常被放入返回的未来中。这就是为什么什么都不打印的原因。如果在未来执行 get
,则会引发异常。
我怎样才能让下面的东西起作用?要点是我想 运行 一个异步的方法(而不是一个函数)。
from multiprocessing import Pool
class Async:
def __init__(self, pool):
self.pool = pool
self.run()
def run(self):
p.apply_async(self.f, (10, ))
def f(self, x):
print x*x
if __name__ == '__main__':
p = Pool(5)
a = Async(p)
p.close()
p.join()
这什么都不打印。
绝对可以在 python 中使用线程池对 class 方法进行线程处理 2 - 下面的程序达到了我的预期。
#!/usr/bin/env python
from multiprocessing.pool import ThreadPool
class TestAsync():
def __init__(self):
pool = ThreadPool(processes = 2)
async_completions = []
for a in range(2):
async_completions.append(pool.apply_async(self.print_int, ( a,)))
for completion in async_completions:
res = completion.get()
print("res = %d" % res)
def print_int(self, value):
print(value)
return (value*10)
a = TestAsync()
问题似乎是由于 multiprocessing
需要 pickle self.f
而绑定方法不可 pickle。有讨论如何解决问题here.
apply_async
显然创建了一个异常,该异常被放入返回的未来中。这就是为什么什么都不打印的原因。如果在未来执行 get
,则会引发异常。