fork download
  1. import threading
  2. import time
  3.  
  4. # Create an Event object
  5. stop_event = threading.Event()
  6. def dump(iterations):
  7. for i in range(iterations):
  8. print('Dump Iteration ',)
  9. def thread_function(iterations, stop_event):
  10. if stop_event.is_set():
  11. print("Thread stopping...")
  12. else:
  13. dump(iterations)
  14.  
  15. def main():
  16. t = threading.Thread(target=thread_function, args=(20, stop_event))
  17. t.start()
  18.  
  19. # Main thread work
  20. for i in range(10):
  21. print(f"Main thread iteration {i}")
  22. time.sleep(1) # Simulate work
  23.  
  24. # Signal the thread to stop
  25. stop_event.set()
  26. t.join() # Wait for the thread to finish
  27.  
  28. if __name__ == "__main__":
  29. main()
  30.  
Success #stdin #stdout 0.03s 10156KB
stdin
Standard input is empty
stdout
Dump Iteration 
Dump Iteration 
Dump Iteration 
Dump Iteration 
Dump Iteration 
Dump Iteration 
Dump Iteration 
Dump Iteration 
Dump Iteration 
Dump Iteration 
Dump Iteration 
Dump Iteration 
Dump Iteration 
Dump Iteration 
Dump Iteration 
Dump Iteration 
Dump Iteration 
Dump Iteration 
Dump Iteration 
Dump Iteration 
Main thread iteration 0
Main thread iteration 1
Main thread iteration 2
Main thread iteration 3
Main thread iteration 4
Main thread iteration 5
Main thread iteration 6
Main thread iteration 7
Main thread iteration 8
Main thread iteration 9