使用阻塞 while 循环的异步执行
Asynchronous execution with blocking while loop
这就是我的场景。我有一个 python 脚本,该脚本 运行 在一个无限循环中接受用户输入。
但是我现在想要另一个函数在阻塞的主循环(等待 python 的 input() 函数)仍然 运行ning 时每 n 秒执行一次操作.我研究了 asyncio 和调度,但它们似乎不适用于阻塞函数调用,还是我弄错了?
我已经研究了多处理,但还不能完全理解我应该如何做到这一点。
编辑:
if __name__ == "__main__":
def survivor():
count = 5
while count:
print("alive")
time.sleep(8)
count -= 1
print("done")
test = JobChainClient()
cli = threading.Thread(name="cli", target=test.getShell())
network = threading.Thread(name="network", target=survivor())
cli.start()
network.start()
print("Done")
此代码获取我的 CLI,它是一个无限循环和我的网络守护程序。当我 运行 这显然有效,但问题是:
(JobChain) > exit
Closing JobChain client now!
alive
alive
alive
我的循环在 exit 命令后中断,仅在另一个线程启动时,我可能只是在这里遗漏了什么,请指正。
您不能同步阻止用户输入。每个阻塞 = 阻塞线程应该同时处理您的其他请求。
为了从异步编程模式中获得最大收益,您必须在任何地方都使用异步。
主要想法是有一个没有任务阻塞的事件循环。任务应该尽快 return 某种承诺,它将在未来某个时候以 return 价值实现。然后 eventloop 可以继续并立即处理您的下一个任务。
如果你真的需要同步阻塞,你应该产生新的线程来做cpu密集绑定任务。
最简单的解决方案是在单独的线程中调用另一个函数(每 n 秒执行一次操作)。
如果您想使用 asyncio,请查看 aioconsole
,它提供了 input()
.
的异步等价物
编辑
关于更新后的问题,正确的发帖方式是:
# note the lack of parentheses after `getShell` - you only
# want to refer to the function, not to call it (yet)
cli = threading.Thread(name="cli", target=test.getShell)
cli.start()
这就是我的场景。我有一个 python 脚本,该脚本 运行 在一个无限循环中接受用户输入。
但是我现在想要另一个函数在阻塞的主循环(等待 python 的 input() 函数)仍然 运行ning 时每 n 秒执行一次操作.我研究了 asyncio 和调度,但它们似乎不适用于阻塞函数调用,还是我弄错了?
我已经研究了多处理,但还不能完全理解我应该如何做到这一点。
编辑:
if __name__ == "__main__":
def survivor():
count = 5
while count:
print("alive")
time.sleep(8)
count -= 1
print("done")
test = JobChainClient()
cli = threading.Thread(name="cli", target=test.getShell())
network = threading.Thread(name="network", target=survivor())
cli.start()
network.start()
print("Done")
此代码获取我的 CLI,它是一个无限循环和我的网络守护程序。当我 运行 这显然有效,但问题是:
(JobChain) > exit
Closing JobChain client now!
alive
alive
alive
我的循环在 exit 命令后中断,仅在另一个线程启动时,我可能只是在这里遗漏了什么,请指正。
您不能同步阻止用户输入。每个阻塞 = 阻塞线程应该同时处理您的其他请求。
为了从异步编程模式中获得最大收益,您必须在任何地方都使用异步。
主要想法是有一个没有任务阻塞的事件循环。任务应该尽快 return 某种承诺,它将在未来某个时候以 return 价值实现。然后 eventloop 可以继续并立即处理您的下一个任务。
如果你真的需要同步阻塞,你应该产生新的线程来做cpu密集绑定任务。
最简单的解决方案是在单独的线程中调用另一个函数(每 n 秒执行一次操作)。
如果您想使用 asyncio,请查看 aioconsole
,它提供了 input()
.
编辑
关于更新后的问题,正确的发帖方式是:
# note the lack of parentheses after `getShell` - you only
# want to refer to the function, not to call it (yet)
cli = threading.Thread(name="cli", target=test.getShell)
cli.start()