import time
import threading
def do_something():
while True:
time.sleep(0.5)
print('I am alive')
def main():
while True:
time.sleep(1)
print('Hello')
daemon_thread = threading.Thread(target=do_something, daemon=True)
daemon_thread.start()
main()
我有没有办法让daemon_thread
从do_something()
之外的3 {秒}进入睡眠状态?我的意思是假设daemon_thread.sleep(3)
?
答案 0 :(得分:1)
创建一个计数器半秒钟,然后使计数器的休眠函数递增:
lock = Lock()
counter = 0
def do_something():
global counter
while True:
time.sleep(0.5)
with lock:
if counter == 0:
print('I am alive')
else:
counter -= 1
def increment(seconds):
global counter
with lock:
counter += 2*seconds
# after starting thread
increment(3) # make the thread wait three seconds before continuing