这是一个实现了
multiprocessing.Queue
对象,可用于
asyncio
的示例。它提供了整个
multiprocessing.Queue
接口,并增加了
coro_get
和
coro_put
方法,它们是可用于从队列中异步获取/放置的
asyncio.coroutine
。实现细节与我的另一个答案的第二个示例基本相同:使用
ThreadPoolExecutor
使得获取/放置变为异步,使用
multiprocessing.managers.SyncManager.Queue
在进程间共享队列。唯一的额外技巧是实现
__getstate__
来保持对象可用于 pickle(即序列化),尽管实例变量使用了不可 pickle 的
ThreadPoolExecutor
。
from multiprocessing import Manager, cpu_count
from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor
def AsyncProcessQueue(maxsize=0):
m = Manager()
q = m.Queue(maxsize=maxsize)
return _ProcQueue(q)
class _ProcQueue(object):
def __init__(self, q):
self._queue = q
self._real_executor = None
self._cancelled_join = False
@property
def _executor(self):
if not self._real_executor:
self._real_executor = ThreadPoolExecutor(max_workers=cpu_count())
return self._real_executor
def __getstate__(self):
self_dict = self.__dict__
self_dict['_real_executor'] = None
return self_dict
def __getattr__(self, name):
if name in ['qsize', 'empty', 'full', 'put', 'put_nowait',
'get', 'get_nowait', 'close']:
return getattr(self._queue, name)
else:
raise AttributeError("'%s' object has no attribute '%s'" %
(self.__class__.__name__, name))
@asyncio.coroutine
def coro_put(self, item):
loop = asyncio.get_event_loop()
return (yield from loop.run_in_executor(self._executor, self.put, item))
@asyncio.coroutine
def coro_get(self):
loop = asyncio.get_event_loop()
return (yield from loop.run_in_executor(self._executor, self.get))
def cancel_join_thread(self):
self._cancelled_join = True
self._queue.cancel_join_thread()
def join_thread(self):
self._queue.join_thread()
if self._real_executor and not self._cancelled_join:
self._real_executor.shutdown()
@asyncio.coroutine
def _do_coro_proc_work(q, stuff, stuff2):
ok = stuff + stuff2
print("Passing %s to parent" % ok)
yield from q.coro_put(ok)
item = q.get()
print("got %s back from parent" % item)
def do_coro_proc_work(q, stuff, stuff2):
loop = asyncio.get_event_loop()
loop.run_until_complete(_do_coro_proc_work(q, stuff, stuff2))
@asyncio.coroutine
def do_work(q):
loop.run_in_executor(ProcessPoolExecutor(max_workers=1),
do_coro_proc_work, q, 1, 2)
item = yield from q.coro_get()
print("Got %s from worker" % item)
item = item + 25
q.put(item)
if __name__ == "__main__":
q = AsyncProcessQueue()
loop = asyncio.get_event_loop()
loop.run_until_complete(do_work(q))
输出:
Passing 3 to parent
Got 3 from worker
got 28 back from parent
正如您所看到的,您可以在父进程或子进程中同步或异步地使用AsyncProcessQueue
。它不需要任何全局状态,并通过将大部分复杂性封装在一个类中,比我的原始回答更加优雅易用。
直接使用套接字可能能够获得更好的性能,但是以跨平台的方式使其工作似乎相当棘手。这种方法的优点是可用于多个工作进程,不需要对自己进行pickle / unpickle等操作。
multiprocessing.Process
创建的。 - balu