Last active
August 3, 2018 09:12
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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