简体   繁体   中英

Python pause thread execution

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.

Use join :

Thread1.join()
Thread2.join()

Also note that setDaemon is the old 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.

The daemon flag indicates that the interpreter needn't wait for a thread. It will exit when only daemon threads are left.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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