Advertisement
DrAungWinHtut

kill_thread.py

Feb 7th, 2024
898
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.12 KB | None | 0 0
  1. import threading
  2. import time
  3.  
  4. exit_event1 = threading.Event()
  5. exit_event2 = threading.Event()
  6.  
  7. def print_numbers(thread_no, exit_event):
  8.     i = 0
  9.     while not exit_event.is_set():
  10.         i += 1
  11.         time.sleep(1)
  12.         print(f'Thread no. {thread_no} - i = {i}')
  13.  
  14. # Create threads
  15. thread1 = threading.Thread(target=print_numbers, args=(1, exit_event1), name='Thread 1')
  16. thread2 = threading.Thread(target=print_numbers, args=(2, exit_event2), name='Thread 2')
  17.  
  18. # Start the threads
  19. thread1.start()
  20. thread2.start()
  21.  
  22. # Wait for user input
  23. while True:
  24.     key = input('Press 1 to exit Thread 1, 2 to exit Thread 2, q to quit: ')
  25.    
  26.     if key == '1':
  27.         exit_event1.set()
  28.         thread1.join()  # Wait for Thread 1 to finish
  29.        
  30.     elif key == '2':
  31.         exit_event2.set()
  32.         thread2.join()  # Wait for Thread 2 to finish
  33.        
  34.     elif key.lower() == 'q':
  35.         exit_event1.set()  # Signal both threads to exit
  36.         exit_event2.set()
  37.         thread1.join()  # Wait for both threads to finish
  38.         thread2.join()
  39.        
  40.     else:
  41.         print("Invalid input. Try again.")
  42.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement