Example of queue operation for multithreaded programming in Python3

  • 2020-05-09 18:51:01
  • OfStack

Python3, open one thread, write an increasing number to the queue at intervals of one second, open another thread, take the number from the queue and print it to the terminal


#! /usr/bin/env python3

import time
import threading
import queue

# 1 Threads, intervals 1 Set the time, put it 1 Ten incrementing Numbers are written to the queue 
#  producers 
class Producer(threading.Thread):

  def __init__(self, work_queue):
    super().__init__() #  You must call 
    self.work_queue = work_queue
    
  def run(self):
    num = 1
    while True:
      self.work_queue.put(num)
      num = num+1
      time.sleep(1) #  suspended 1 seconds 

# 1 Thread, take the number from the queue, and display it to the terminal 
class Printer(threading.Thread):

  def __init__(self, work_queue):
    super().__init__() #  You must call 
    self.work_queue = work_queue

  def run(self):
    while True:
      num = self.work_queue.get() #  When the queue is empty, it blocks until there is data 
      print(num)

def main():
  work_queue = queue.Queue()

  producer = Producer(work_queue)
  producer.daemon = True #  The child thread exits when the main thread exits 
  producer.start()

  printer = Printer(work_queue)
  printer.daemon = True #  The child thread exits when the main thread exits 
  printer.start()

  work_queue.join() #  The main thread will stop here until all the Numbers are filled get() And, task_done() Because there is no call task_done() Will be here 1 Block until the user presses ^C

if __name__ == '__main__':
  main()

queue is thread safe and is accessed from multiple threads without locking.
If work_queue.task_done () is called after work_queue.get (), work_queue.join () is returned when the queue is empty.
Here work_queue.put () is to put something into the queue at a fixed interval of 1. If work_queue.task_done () is called, after the number 1 is get(), join() returns when the queue is empty, and the program ends.
So it only prints 1 and then exits.
So in this usage scenario, you can't call task_done(), and the program will loop through 1.


Related articles: