【发布时间】:2017-06-21 19:36:54
【问题描述】:
所以我使用 Python asyncio 模块(在 Linux 上)来启动一个子进程,然后异步监视它。我的代码运行良好...在 主线程 上运行时。但是当我在工作线程上运行它时,它会挂起,并且永远不会调用 process_exited 回调。
我怀疑这实际上可能是某种未记录的缺陷或在工作线程上运行subprocess_exec 的问题,可能与实现如何处理后台线程中的信号有关。但也可能只是我把事情搞砸了。
一个简单的、可重现的例子如下:
class MyProtocol(asyncio.SubprocessProtocol):
def __init__(self, done_future):
super().__init__()
self._done_future = done_future
def pipe_data_received(self, fd, data):
print("Received:", len(data))
def process_exited(self):
print("PROCESS EXITED!")
self._done_future.set_result(None)
def run(loop):
done_future = asyncio.Future(loop = loop)
transport = None
try:
transport, protocol = yield from loop.subprocess_exec(
lambda : MyProtocol(done_future),
"ls",
"-lh",
stdin = None
)
yield from done_future
finally:
if transport: transport.close()
return done_future.result()
def run_loop():
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop) # bind event loop to current thread
try:
return loop.run_until_complete(run(loop))
finally:
loop.close()
所以在这里,我设置了一个asyncio事件循环来执行shell命令ls -lh,然后在从子进程接收到数据时触发回调,并在子进程退出时触发另一个回调。
如果我直接在 Python 程序的主线程中调用run_loop(),一切都会好起来的。但如果我说:
t = threading.Thread(target = run_loop)
t.start()
t.join()
然后发生的情况是pipe_data_received()回调被成功调用,但process_exited()从未被调用,程序只是挂起。
在谷歌搜索并查看了unix_events.py 实现的asyncio 源代码之后,我发现可能需要手动将我的事件循环附加到全局“child watcher”对象,如下所示:
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop) # bind event loop to current thread
asyncio.get_child_watcher().attach_loop(loop)
显然,子观察者是一个(未记录的)对象,负责在后台调用waitpid(或类似的东西)。但是当我尝试这个并在后台线程中运行 run_event_loop() 时,我得到了错误:
File "/usr/lib/python3.4/asyncio/unix_events.py", line 77, in add_signal_handler
raise RuntimeError(str(exc))
RuntimeError: set_wakeup_fd only works in main thread
所以这里看起来实现实际上做了检查以确保信号处理程序只能在主线程上使用,这让我相信在当前的实现中,实际上在后台线程上使用subprocess_exec , 根本不可能不改变 Python 源代码本身。
我说的对吗?可悲的是,asyncio 模块的文档非常少,所以我很难对我的结论充满信心。我可能只是做错了什么。
【问题讨论】:
标签: python linux python-3.x asynchronous python-asyncio