python multithreaded neutron thread and main thread mutual communication method

  • 2021-01-25 07:45:06
  • OfStack

Requirement: The main thread starts multiple threads to do work. Each thread has a different time to complete, but notifies the main thread when it is done

The following code:


#!/usr/bin/python
# coding:utf8
'''
 Multithreading and queue Cooperate with the use of the child thread and the main thread to communicate with each other 
'''
import threading
 
__author__ = "Kenny.Li"
 
import Queue
import time
import random
 
q = Queue.Queue()
 
 
class MyThread(threading.Thread):
 def __init__(self, q, t, j):
  super(MyThread, self).__init__()
  self.q = q
  self.t = t
  self.j = j
 
 def run(self):
  time.sleep(self.j)
  self.q.put(u" I am the first %d A thread, I sleep %d seconds , The current time is %s" % (self.t, self.j, time.ctime()))
 
 
count = 0
threads = []
for i in xrange(15):
 j = random.randint(1, 8)
 threads.append(MyThread(q, i, j))
for mt in threads:
 mt.start()
print "start time: ", time.ctime()
while True:
 if not q.empty():
  print q.get()
  count += 1
 if count == 15:
  break

The above code is explained below:

1, q is an instantiated queue object with FIFO properties. First, define a thread class of your own and override 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: Queue the messages that each child thread will return to the main thread using the q.put () method.

3. From line 31, generate 15 child threads and add them to the thread group. Each thread will randomly sleep for 1-8 seconds (the simulated time of each thread is different).

4, Lines 34-35, the loop starts all child threads

5. Line 36, print the start time

6. Through one while cycle, when the q queue is not empty, the q.get() method is used to read the messages in the queue q in a cycle, and the counter is increased by 1 each time. When the counter reaches 15, it is proved that all the messages of child threads have been obtained, and the cycle stops.


Related articles: