Demand:The main thread opens multiple threads to do work, each thread needs a different amount of time to complete, but after the work is done they all have to be notified to the main thread.
Code below:
#!/usr/bin/python # coding:utf8 ''' Example of using multithreading and queue together to realize sub-threads and main threads communicating with each other ''' import threading __author__ = "" import Queue import time import random q = () class MyThread(): def __init__(self, q, t, j): super(MyThread, self).__init__() = q = t = j def run(self): () (u"I'm the %dth thread, I've been asleep for %d seconds, and the current time is %s." % (, , ())) count = 0 threads = [] for i in xrange(15): j = (1, 8) (MyThread(q, i, j)) for mt in threads: () print "start time: ", () while True: if not (): print () count += 1 if count == 15: break
The above code is explained below:
1, q is an instantiated queue object with FIFOness. First define a thread class of your own, overriding the run method. Note that the q queue is passed into the constructor to receive the messages that each thread needs to return.
2, line 26, via the () method, stores in a queue the messages that each child thread is to return to the main thread.
3, starting from line 31, generate 15 sub-threads and add them to the thread group, each thread randomly sleeps for 1-8 seconds (to simulate different lengths of time for each thread to work)
4, lines 34-35, loop to turn on all child threads
5, line 36, print start time
6, through a while loop, when the q queue is not empty, through the () method, the loop reads the messages in queue q, each time the counter plus one, when the counter reaches 15, proving that all the sub-threads of the message has been obtained, at this time the loop stops.
Above this python multithreading in the sub-thread and the main thread to communicate with each other method is all I have shared with you, I hope to be able to give you a reference, and I hope you support me more.