From f1b9342f98fb1ad80ca6160e163d7398fa87ea83 Mon Sep 17 00:00:00 2001 From: dbarzin Date: Sat, 4 Mar 2023 10:33:35 +0100 Subject: [PATCH] work on example --- tests/thread.py | 36 ++++++++++++++++-------------------- 1 file changed, 16 insertions(+), 20 deletions(-) diff --git a/tests/thread.py b/tests/thread.py index 2845b22..5e7869d 100755 --- a/tests/thread.py +++ b/tests/thread.py @@ -4,53 +4,48 @@ import queue import threading import time - -exitFlag = 0 +exitFlag = False class myThread (threading.Thread): - def __init__(self, threadID, name, q): + def __init__(self, id, q): threading.Thread.__init__(self) - self.threadID = threadID - self.name = name + self.id = id self.q = q def run(self): - print("Starting " + self.name) - process_data(self.name, self.q) - print("Exiting " + self.name) + print(f"Thread-{self.id} Starting ") + process_data(self.id, self.q) + print(f"Thread-{self.id} Done.") -def process_data(threadName, q): +def process_data(id, q): while not exitFlag: queueLock.acquire() if not workQueue.empty(): data = q.get() queueLock.release() - print("%s processing %s" % (threadName, data)) + print(f"Thread-{id} processing {data}") else: queueLock.release() time.sleep(1) -threadList = ["Thread-1", "Thread-2"] -nameList = ["One", "Two", "Three", "Four", "Five", "Six", 'Seven'] +maxThread = 2 +workList = ["One", "Two", "Three", "Four", "Five", "Six", 'Seven'] queueLock = threading.Lock() -workQueue = queue.Queue(10) +workQueue = queue.Queue() threads = [] -threadID = 1 - # Create new threads -for tName in threadList: - thread = myThread(threadID, tName, workQueue) +for i in range(maxThread): + thread = myThread(i, workQueue) thread.start() threads.append(thread) - threadID += 1 # Fill the queue queueLock.acquire() -for word in nameList: +for word in workList: workQueue.put(word) queueLock.release() @@ -59,9 +54,10 @@ while not workQueue.empty(): pass # Notify threads it's time to exit -exitFlag = 1 +exitFlag = True # Wait for all threads to complete for t in threads: t.join() + print("Exiting Main Thread")