In this post i extend an example found on stackoverflow.com, here’s how to launch two simultaneous threads and stop them after 5 seconds.
import threading
import time
def doit(arg):
t = threading.currentThread()
while getattr(t, "do_run", True):
print ("working on %s" % arg)
time.sleep(1)
print("Stopping as you wish.")
def main():
t1 = threading.Thread(target=doit, args=("task 1",))
t1.start()
t2 = threading.Thread(target=doit, args=("task 2",))
t2.start()
time.sleep(5)
t1.do_run = False
t1.join()
t2.do_run = False
t2.join()
if __name__ == "__main__":
main()