简体   繁体   中英

Python threading with multiple target functions

I'm currently trying to get my program to process several jobs from several classes and I can't get it to actually perform the process() function. This is based on one of the topics found online.

class myThread (threading.Thread):
        def __init__(self, threadID, name, q):
            threading.Thread.__init__(self)
            self.threadID = threadID
            self.name = name
            self.q = q

        def run(self):
            print ("Starting " + self.name)
            myThread.process_data(self.name, self.q)
            print ("Exiting " + self.name)

        def process_data(threadName, q):
            while not exitFlag:
                queueLock.acquire()
                if not workQueue.empty():
                    data = q.get()
                    queueLock.release()
                    print ("{0} processing {1}".format(threadName, data))
                else:
                    queueLock.release()
                time.sleep(1)

threadList = ["Thread-1", "Thread-2", "Thread-3"]
nameList = [myclass1.process, myclass2.process, myclass3.process, myclass5.process, myclass6.process]
queueLock = threading.Lock()
workQueue = queue.Queue()
threads = []
threadID = 1
exitFlag = 0
# Create new threads
for tName in threadList:
    thread = myThread(threadID, tName, workQueue)
    thread.start()
    threads.append(thread)
    threadID += 1

# Fill the queue
queueLock.acquire()
for word in nameList:
    workQueue.put(word)
queueLock.release()
    # Wait for queue to empty
while not workQueue.empty():
    pass
    # Notify threads it's time to exit
exitFlag = 1
    # Wait for all threads to complete
for t in threads:
    t.join()
print ("Exiting Main Thread")    

This returns as expected:

Starting Thread-1
Starting Thread-2
Starting Thread-3
Thread-1 processing <bound method myclass1.process of <myclass1.myclass1 object at 0x7fc163542e10>>
Thread-2 processing <bound method myclass2.process of <myclass2.myclass2 object at 0x7fc163542dd8>>
Thread-3 processing <bound method myclass3.process of <myclass3.myclass3 object at 0x7fc163542a20>>
Thread-1 processing <bound method myclass4.process of <myclass4.myclass4 object at 0x7fc16354e080>>
Thread-3 processing <bound method myclass5.process of <myclass5.myclass5 object at 0x7fc16354e438>>
Exiting Thread-1
Exiting Thread-3
Exiting Thread-2
Exiting Main Thread

I currently use Thread(target=myclassX.process) but now it's different... How could I modify my program to actually make it perform the process() function for each class instead of just adding it as a bound method in the queue?

汤姆·道尔顿在评论中给了我答案。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM