我有一个应用程序,可以让我选择是使用线程还是进程:
def _get_future(self, workers):
if self.config == "threadpool":
self.logger.debug("using thread pools")
executor = ThreadPoolExecutor(max_workers=workers)
else:
self.logger.debug("using process pools")
executor = ProcessPoolExecutor(max_workers=workers)
return executor
Run Code Online (Sandbox Code Playgroud)
后来我执行代码:
self.executor = self._get_future()
for component in components:
self.logger.debug("submitting {} to future ".format(component))
self.future_components.append(self.executor.submit
(self._send_component, component))
# Wait for all tasks to finish
while self.future_components:
self.future_components.pop().result()
Run Code Online (Sandbox Code Playgroud)
当我使用进程时,我的应用程序会卡住。_send_component 方法永远不会被调用。当我使用线程时一切正常。
问题在于命令式方法,这是函数式方法的用例。
self._send_component 是类的成员函数。单独的进程意味着没有联合内存来共享变量。
解决方案是重写代码,使 _send_component 成为静态方法。