Python暂停线程执行

发布于 2024-12-08 10:28:23 字数 474 浏览 0 评论 0原文

有没有办法永久“暂停”应用程序的主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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

不语却知心 2024-12-15 10:28:23

如果您不在线程上执行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.

撕心裂肺的伤痛 2024-12-15 10:28:23

使用 join

Thread1.join()
Thread2.join()

另请注意 setDaemon 是旧的 API。

Thread1.daemon = True

是现在的首选方式。

Use join:

Thread1.join()
Thread2.join()

Also note that setDaemon is the old API.

Thread1.daemon = True

is the preferred way now.

浅暮の光 2024-12-15 10:28:23

守护线程的全部目的是阻止应用程序在其中任何一个仍在运行时被终止。您显然希望线程保持应用程序进程处于活动状态,因此不要将它们设置为守护进程。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文