Created
April 24, 2023 13:15
-
-
Save saurabh47/38fd37c58fef5ddc2fc41d713a5f034d to your computer and use it in GitHub Desktop.
Python Multi Threading Example with Queue with Pooling workers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import queue | |
import threading | |
import time | |
def worker(threadId, q): | |
while True: | |
item = q.get() | |
if item is None: | |
q.task_done() | |
continue | |
# Process the item here | |
print("Processing item:", item * 2, " Thread Id:", threadId) | |
time.sleep(1) # Simulate some work | |
q.task_done() | |
q = queue.Queue() | |
num_threads = 3 | |
threads = [] | |
for i in range(num_threads): | |
t = threading.Thread(target=worker, args=(i, q)) | |
t.daemon = True # Set the thread as a daemon to exit when the main program exits | |
t.start() | |
threads.append(t) | |
while True: | |
user_input = input("Enter a task to be processed: ") | |
if user_input == "exit": | |
break | |
q.put(user_input) | |
print("Exiting...") | |
# Stop the worker threads by sending a None value to the queue for each thread | |
# for i in range(num_threads): | |
# q.put(None) | |
# | |
# # Wait for the worker threads to exit | |
# for t in threads: | |
# t.join() | |
# | |
# print("All threads have exited") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment