我有創建子進程,使用未來接收結果,然後殺死其中一些需要時的要求。集成multiprocessing.Process與concurrent.future._base.Future
爲此,我分類了multiprocessing.Process類,並從start()方法返回Future對象。
問題是我無法在cb()函數中接收到結果,因爲它永遠不會被調用。
請幫助/建議如果這可以用其他方式完成,或者我在當前實現中丟失了什麼?
以下是我目前的做法
from multiprocessing import Process, Queue
from concurrent.futures import _base
import threading
from time import sleep
def foo(x,q):
print('result {}'.format(x*x))
result = x*x
sleep(5)
q.put(result)
class MyProcess(Process):
def __init__(self, target, args):
super().__init__()
self.target = target
self.args = args
self.f = _base.Future()
def run(self):
q = Queue()
worker_thread = threading.Thread(target=self.target, args=(self.args+ (q,)))
worker_thread.start()
r = q.get(block=True)
print('setting result {}'.format(r))
self.f.set_result(result=r)
print('done setting result')
def start(self):
f = _base.Future()
run_thread = threading.Thread(target=self.run)
run_thread.start()
return f
def cb(future):
print('received result in callback {}'.format(future))
def main():
p1 = MyProcess(target=foo, args=(2,))
f = p1.start()
f.add_done_callback(fn=cb)
sleep(10)
if __name__ == '__main__':
main()
print('Main thread dying')
感謝您的回覆。這是一個非常愚蠢的錯誤。感謝您的注意! :) –