Python暂停线程执行
有没有办法永久“暂停”应用程序的主Python线程?
我有一些代码可以触发两个线程
class start():
def __init__(self):
Thread1= functions.threads.Thread1()
Thread1.setDaemon(True)
Thread1.start()
Thread2= functions.threads.Thread2()
Thread2.setDaemon(True)
Thread2.start()
#Stop thread here
,当程序到达该函数的末尾时,它会退出(之后主线程没有其他事情可做),从而杀死无限运行的线程(循环)。如何阻止主进程退出?我可以使用 while True: None 循环来完成此操作,但这会占用大量 CPU,并且可能有更好的方法。
Is there a way to "pause" the main python thread of an application perminantly?
I have some code that fires off two threads
class start():
def __init__(self):
Thread1= functions.threads.Thread1()
Thread1.setDaemon(True)
Thread1.start()
Thread2= functions.threads.Thread2()
Thread2.setDaemon(True)
Thread2.start()
#Stop thread here
At the moment, when the program gets to the end of that function it exits (There is nothing else for the main thread to do after that), killing the threads which run infinately (Looping). How do I stop the main process from exiting? I can do it with a while True: None
loop but that uses a lot of CPU and there's probably a better way.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您不在线程上执行
setDaemon(True)
,则只要线程运行,进程就会继续运行。守护进程标志表明解释器不需要等待线程。当只剩下守护线程时它将退出。
If you don't do
setDaemon(True)
on the threads, the process will keep running as long as the threads run for.The daemon flag indicates that the interpreter needn't wait for a thread. It will exit when only daemon threads are left.
使用 join:
另请注意
setDaemon
是旧的 API。是现在的首选方式。
Use join:
Also note that
setDaemon
is the old API.is the preferred way now.
守护线程的全部目的是不阻止应用程序在其中任何一个仍在运行时被终止。您显然希望线程保持应用程序进程处于活动状态,因此不要将它们设置为守护进程。
The whole point of daemon threads is to not prevent the application from being terminated if any of them is still running. You obviously want your threads to keep the application process alive, so don't make them daemons.