Skip to content

Instantly share code, notes, and snippets.

@7185
Last active August 3, 2018 09:12
Show Gist options
  • Save 7185/5a2bc759ec798d32c9dd704099d0287d to your computer and use it in GitHub Desktop.
Save 7185/5a2bc759ec798d32c9dd704099d0287d to your computer and use it in GitHub Desktop.
a way to stop a long running thread before creating a new one
import threading
from time import sleep
tn = 0
def func(id):
tid = tn
for i in range(10):
if tn != tid:
break
print('id:', id, '/ threads:', len(threading.enumerate()), '/ timer:', i)
sleep(1)
tn += 1
t1 = threading.Thread(target=func, args=('A'))
t1.daemon = True
t1.start()
sleep(3)
tn += 1
t2 = threading.Thread(target=func, args=('B'))
t2.daemon = True
t2.start()
while len(threading.enumerate()) > 1:
pass
@7185
Copy link
Author

7185 commented Aug 3, 2018

note: obviously the first thread can stop slightly after the second one has been created, that's why the output displays 3 threads (main + A + B) at some point

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment