简体   繁体   English

Python暂停线程执行

[英]Python pause thread execution

Is there a way to "pause" the main python thread of an application perminantly? 有没有办法永久地“暂停”应用程序的主要python线程?

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. 我可以用while True: None循环来做到这一点,但这会占用大量CPU,并且可能有更好的方法。

Use join : 使用join

Thread1.join()
Thread2.join()

Also note that setDaemon is the old API. 另请注意, setDaemon是旧的API。

Thread1.daemon = True

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. 显然,您希望线程使应用程序进程保持活动状态,因此不要使它们成为守护进程。

If you don't do setDaemon(True) on the threads, the process will keep running as long as the threads run for. 如果您不对线程执行setDaemon(True) ,则只要线程运行,该进程将一直运行。

The daemon flag indicates that the interpreter needn't wait for a thread. 守护程序标志指示解释器无需等待线程。 It will exit when only daemon threads are left. 仅保留后台驻留程序线程时,它将退出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM