gpt4 book ai didi

python - time.sleep 阻塞 while 线程中的循环

转载 作者:行者123 更新时间:2023-11-30 22:29:45 24 4
gpt4 key购买 nike

当我在线程中运行 While True 循环并使用 time.sleep() 函数时,循环将停止循环。

我正在使用代码:

import threading
from time import sleep

class drive_worker(threading.Thread):

def __init__(self):
super(drive_worker, self).__init__()
self.daemon = True
self.start()

def run(self):
while True:
print('loop')
#some code
time.sleep(0.5)

要启动线程,我使用代码:

thread = drive_worker()

最佳答案

循环停止,因为您将线程标记为守护进程。当只剩下守护线程运行时,程序终止。

self.daemon = True # remove this statement and the code should work as expected

或者让主线程等待守护线程完成

dthread = drive_worker()
# no call to start method since your constructor does that
dthread.join() #now the main thread waits for the new thread to finish

关于python - time.sleep 阻塞 while 线程中的循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46256057/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com