Jon*_*ler 3 python concurrency multithreading multiprocessing
有没有办法创建一个回调,只要通过启动的子进程将某些内容发送到主进程,该回调就会执行multiprocessing?到目前为止我能想到的最好的是:
import multiprocessing as mp
import threading
import time
class SomeProcess(mp.Process):
def run(self):
while True
time.sleep(1)
self.queue.put(time.time())
class ProcessListener(threading.Thread):
def run(self):
while True:
value = self.queue.get()
do_something(value)
if __name__ = '__main__':
queue = mp.Queue()
sp = SomeProcess()
sp.queue = queue
pl = ProcessListener()
pl.queue = queue
sp.start()
pl.start()
Run Code Online (Sandbox Code Playgroud)
不,除了您已经发布的方法之外,没有其他干净的方法可以做到这一点。
这就是实际实施的方式concurrent.fututes.ProcessPoolExecutor和实施方式multiprocessing.Pool。它们有一个专用线程,用于耗尽任务/结果队列并运行任何关联的回调。
如果你想节省一些资源,你可以SimpleQueue在这种情况下使用 a 。