且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何停止在执行程序中运行的循环?

更新时间:2023-01-31 11:01:58

是否有一种简单的方法可以停止线程或循环?

Is there an easy way to stop the thread or loop?

您不能强行停止线程.要实现取消功能,您的函数需要接受 should_stop 参数,例如 threading.Event,偶尔检查是否已设置.

You cannot forcefully stop a thread. To implement the cancel functionality, your function will need to accept a should_stop argument, for example an instance of threading.Event, and occasionally check if it has been set.

如果您确实需要强制停止,并且您的函数可以通过 多处理,您可以在一个单独的进程中运行它并在它应该停止时终止该进程.请参阅此答案,了解在 asyncio 上下文中对该方法的详细说明.

If you really need a forceful stop, and if your function is runnable in a separate process through multiprocessing, you can run it in a separate process and kill the process when it is supposed to stop. See this answer for an elaboration of that approach in the context of asyncio.