You cannot "switch" threads. So once you're done with your main thread, you have to wait for the other threads to terminate using the method join
. But note this:
- Since the
join
method is not interruptible withKeyboardInterrupt
, you need to specify a timeout and loop over to detect user interrupts. - Since you can't force a thread to terminate, you have to implement a stop mecanism using threading.Event for instance
- You also need to use threading.Lock to prevent concurrent access on shared resources, like
sys.stdout
(used when you print)
I gathered these aspects in a class called ThreadHandler
, please have a look:
import threading, time
def printCount(lock, stop):
with lock:
print "Thread B started"
x = 0
while not stop.is_set():
time.sleep(1)
x = x + 1
with lock:
print x
class ThreadHandler():
STEP = 0.2
def __init__(self, target):
self.lock = threading.Lock()
self.stop = threading.Event()
args = (self.lock, self.stop)
self.thread = threading.Thread(target=target, args=args)
def start(self):
self.thread.start()
def join(self):
while self.thread.is_alive():
try:
self.thread.join(self.STEP)
except KeyboardInterrupt:
self.stop.set()
## User Code ##
print "begin!"
handler = ThreadHandler(target=printCount)
handler.start()
with handler.lock:
print "woop!"
handler.join()