Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import threading
- import time
- exit_event1 = threading.Event()
- exit_event2 = threading.Event()
- def print_numbers(thread_no, exit_event):
- i = 0
- while not exit_event.is_set():
- i += 1
- time.sleep(1)
- print(f'Thread no. {thread_no} - i = {i}')
- # Create threads
- thread1 = threading.Thread(target=print_numbers, args=(1, exit_event1), name='Thread 1')
- thread2 = threading.Thread(target=print_numbers, args=(2, exit_event2), name='Thread 2')
- # Start the threads
- thread1.start()
- thread2.start()
- # Wait for user input
- while True:
- key = input('Press 1 to exit Thread 1, 2 to exit Thread 2, q to quit: ')
- if key == '1':
- exit_event1.set()
- thread1.join() # Wait for Thread 1 to finish
- elif key == '2':
- exit_event2.set()
- thread2.join() # Wait for Thread 2 to finish
- elif key.lower() == 'q':
- exit_event1.set() # Signal both threads to exit
- exit_event2.set()
- thread1.join() # Wait for both threads to finish
- thread2.join()
- else:
- print("Invalid input. Try again.")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement