什么是Python式的无所事事的方式?

2024-09-28 03:20:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要我的主程序,在某个时候,什么都不做-永远(有一些线程在前面开始,做一些工作)。在

我想知道Python是怎么做到的。我特别想避免在这个虚无中失去CPU周期。在

我的直接猜测是time.sleep(100000),其中{}对于我的程序生命周期来说足够大了。它很管用,但在美学上并不令人愉快。我检查了运行以下内容的python会话的CPU负载:不可测量(接近于零)。在

我也试过了

while True:
    pass

它看起来不错,但对CPU的影响是巨大的(约25%)。在

one-- and preferably only one --obvious way to do it吗?在


Tags: and程序trueonlytimesleeppasscpu
1条回答
网友
1楼 · 发布于 2024-09-28 03:20:09

如果要等待线程退出,请使用^{}

join([timeout])

Wait until the thread terminates. This blocks the calling thread until the thread whose join() method is called terminates – either normally or through an unhandled exception – or until the optional timeout occurs.

用法示例:

import threading
t = threading.Thread(name='non-daemon', target=non_daemon)

t.start() # This will not block
t.join() #  This is blocking

相关问题 更多 >

    热门问题