我一直在寻找一个简单的python线程池模式的良好实现,但真的找不到任何适合我需要的东西。我正在使用 python 2.7 并且我发现的所有模块都不起作用,或者没有正确处理工作人员中的异常。我想知道是否有人知道可以提供我正在搜索的功能类型的库。非常感谢帮助。
多处理
我的第一次尝试是使用内置multiprocessing
模块,但由于它不使用线程而是使用子进程,我们遇到了无法腌制对象的问题。不去这里。
from multiprocessing import Pool
class Sample(object):
def compute_fib(self, n):
phi = (1 + 5**0.5) / 2
self.fib = int(round((phi**n - (1-phi)**n) / 5**0.5))
samples = [Sample() for i in range(8)]
pool = Pool(processes=8)
for s in samples: pool.apply_async(s.compute_fib, [20])
pool.join()
for s in samples: print s.fib
# PicklingError: Can't pickle <type 'instancemethod'>: attribute lookup __builtin__.instancemethod failed
期货
所以我看到这里有 python 3.2 的一些很酷的并发特性的后端口。这似乎完美且易于使用。问题是,当您在其中一名工作人员中遇到异常时,您只能获得异常类型,例如“ZeroDivisionError”,但没有回溯,因此没有指示哪一行导致了异常。代码变得无法调试。不去。
from concurrent import futures
class Sample(object):
def compute_fib(self, n):
phi = (1 + 5**0.5) / 2
1/0
self.fib = int(round((phi**n - (1-phi)**n) / 5**0.5))
samples = [Sample() for i in range(8)]
pool = futures.ThreadPoolExecutor(max_workers=8)
threads = [pool.submit(s.compute_fib, 20) for s in samples]
futures.wait(threads, return_when=futures.FIRST_EXCEPTION)
for t in threads: t.result()
for s in samples: print s.fib
# futures-2.1.3-py2.7.egg/concurrent/futures/_base.pyc in __get_result(self)
# 354 def __get_result(self):
# 355 if self._exception:
#--> 356 raise self._exception
# 357 else:
# 358 return self._result
#
# ZeroDivisionError: integer division or modulo by zero
工人池
我在这里找到了这种模式的另一个实现。这次发生异常时,它会被打印出来,但是我的 ipython 交互式解释器处于挂起状态,需要从另一个 shell 中终止。不去。
import workerpool
class Sample(object):
def compute_fib(self, n):
phi = (1 + 5**0.5) / 2
1/0
self.fib = int(round((phi**n - (1-phi)**n) / 5**0.5))
samples = [Sample() for i in range(8)]
pool = workerpool.WorkerPool(size=8)
for s in samples: pool.map(s.compute_fib, [20])
pool.wait()
for s in samples: print s.fib
# ZeroDivisionError: integer division or modulo by zero
# ^C^C^C^C^C^C^C^C^D^D
# $ kill 1783
线程池
这里还有另一个实现。这次发生异常时,它会打印到 ,stderr
但脚本不会中断,而是继续执行,这违背了异常的目的,并且会使事情变得不安全。还是不能用。
import threadpool
class Sample(object):
def compute_fib(self, n):
phi = (1 + 5**0.5) / 2
1/0
self.fib = int(round((phi**n - (1-phi)**n) / 5**0.5))
samples = [Sample() for i in range(8)]
pool = threadpool.ThreadPool(8)
requests = [threadpool.makeRequests(s.compute_fib, [20]) for s in samples]
requests = [y for x in requests for y in x]
for r in requests: pool.putRequest(r)
pool.wait()
for s in samples: print s.fib
# ZeroDivisionError: integer division or modulo by zero
# ZeroDivisionError: integer division or modulo by zero
# ZeroDivisionError: integer division or modulo by zero
# ZeroDivisionError: integer division or modulo by zero
# ZeroDivisionError: integer division or modulo by zero
# ZeroDivisionError: integer division or modulo by zero
# ZeroDivisionError: integer division or modulo by zero
# ZeroDivisionError: integer division or modulo by zero
#---> 17 for s in samples: print s.fib
#
#AttributeError: 'Sample' object has no attribute 'fib'
- 更新 -
看来,关于futures
库,python 3 的行为与 python 2 不同。
futures_exceptions.py
:
from concurrent.futures import ThreadPoolExecutor, as_completed
def div_zero(x):
return x / 0
with ThreadPoolExecutor(max_workers=4) as executor:
futures = executor.map(div_zero, range(4))
for future in as_completed(futures): print(future)
Python 2.7.6输出:
Traceback (most recent call last):
File "...futures_exceptions.py", line 12, in <module>
for future in as_completed(futures):
File "...python2.7/site-packages/concurrent/futures/_base.py", line 198, in as_completed
with _AcquireFutures(fs):
File "...python2.7/site-packages/concurrent/futures/_base.py", line 147, in __init__
self.futures = sorted(futures, key=id)
File "...python2.7/site-packages/concurrent/futures/_base.py", line 549, in map
yield future.result()
File "...python2.7/site-packages/concurrent/futures/_base.py", line 397, in result
return self.__get_result()
File "...python2.7/site-packages/concurrent/futures/_base.py", line 356, in __get_result
raise self._exception
ZeroDivisionError: integer division or modulo by zero
Python 3.3.2输出:
Traceback (most recent call last):
File "...futures_exceptions.py", line 11, in <module>
for future in as_completed(futures):
File "...python3.3/concurrent/futures/_base.py", line 193, in as_completed
with _AcquireFutures(fs):
File "...python3.3/concurrent/futures/_base.py", line 142, in __init__
self.futures = sorted(futures, key=id)
File "...python3.3/concurrent/futures/_base.py", line 546, in result_iterator
yield future.result()
File "...python3.3/concurrent/futures/_base.py", line 392, in result
return self.__get_result()
File "...python3.3/concurrent/futures/_base.py", line 351, in __get_result
raise self._exception
File "...python3.3/concurrent/futures/thread.py", line 54, in run
result = self.fn(*self.args, **self.kwargs)
File "...futures_exceptions.py", line 7, in div_zero
return x / 0
ZeroDivisionError: division by zero