Reputation: 3699
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()
Is there a way I be able to put daemon_thread
to sleep for example for 3 seconds from outside of do_something()
? I mean something hypothetical like daemon_thread.sleep(3)
?
Upvotes: 0
Views: 69
Reputation: 1602
Create a counter for half seconds and then make the sleep function increment that counter:
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
Upvotes: 1