2023-03-03 21:36:34 +01:00
|
|
|
#!/usr/bin/python3
|
|
|
|
|
|
|
|
import queue
|
|
|
|
import threading
|
|
|
|
import time
|
|
|
|
|
2023-03-04 10:33:35 +01:00
|
|
|
exitFlag = False
|
2023-03-03 21:36:34 +01:00
|
|
|
|
|
|
|
|
|
|
|
class myThread (threading.Thread):
|
2023-03-04 10:33:35 +01:00
|
|
|
def __init__(self, id, q):
|
2023-03-03 21:36:34 +01:00
|
|
|
threading.Thread.__init__(self)
|
2023-03-04 10:33:35 +01:00
|
|
|
self.id = id
|
2023-03-03 21:36:34 +01:00
|
|
|
self.q = q
|
|
|
|
|
|
|
|
def run(self):
|
2023-03-04 10:33:35 +01:00
|
|
|
print(f"Thread-{self.id} Starting ")
|
2023-03-04 17:51:50 +01:00
|
|
|
self.process_data()
|
2023-03-04 10:33:35 +01:00
|
|
|
print(f"Thread-{self.id} Done.")
|
2023-03-03 21:36:34 +01:00
|
|
|
|
2023-03-04 17:51:50 +01:00
|
|
|
def process_data(self):
|
|
|
|
while not exitFlag:
|
|
|
|
queueLock.acquire()
|
|
|
|
if not workQueue.empty():
|
|
|
|
data = self.q.get()
|
|
|
|
queueLock.release()
|
|
|
|
print(f"Thread-{self.id} processing {data}")
|
|
|
|
else:
|
|
|
|
queueLock.release()
|
|
|
|
time.sleep(1)
|
2023-03-03 21:36:34 +01:00
|
|
|
|
|
|
|
|
2023-03-04 10:33:35 +01:00
|
|
|
maxThread = 2
|
|
|
|
workList = ["One", "Two", "Three", "Four", "Five", "Six", 'Seven']
|
2023-03-03 21:36:34 +01:00
|
|
|
queueLock = threading.Lock()
|
2023-03-04 10:33:35 +01:00
|
|
|
workQueue = queue.Queue()
|
2023-03-03 21:36:34 +01:00
|
|
|
threads = []
|
|
|
|
|
|
|
|
# Create new threads
|
2023-03-04 10:33:35 +01:00
|
|
|
for i in range(maxThread):
|
|
|
|
thread = myThread(i, workQueue)
|
2023-03-03 21:36:34 +01:00
|
|
|
thread.start()
|
|
|
|
threads.append(thread)
|
|
|
|
|
|
|
|
# Fill the queue
|
|
|
|
queueLock.acquire()
|
2023-03-04 10:33:35 +01:00
|
|
|
for word in workList:
|
2023-03-03 21:36:34 +01:00
|
|
|
workQueue.put(word)
|
|
|
|
queueLock.release()
|
|
|
|
|
|
|
|
# Wait for queue to empty
|
|
|
|
while not workQueue.empty():
|
|
|
|
pass
|
|
|
|
|
|
|
|
# Notify threads it's time to exit
|
2023-03-04 10:33:35 +01:00
|
|
|
exitFlag = True
|
2023-03-03 21:36:34 +01:00
|
|
|
|
|
|
|
# Wait for all threads to complete
|
|
|
|
for t in threads:
|
|
|
|
t.join()
|
2023-03-04 10:33:35 +01:00
|
|
|
|
2023-03-03 21:36:34 +01:00
|
|
|
print("Exiting Main Thread")
|