Example of queue operation for multi-thread programming in Python3, and multi-thread programming in python3
Python3: open a thread and write an incremental number to the queue at intervals of 1 second. Then open another thread to extract the number from the queue and print it to the terminal.
#! /Usr/bin/env python3import timeimport threadingimport queue # A thread writes an incremental number to the queue at a certain interval # Producer class Producer (threading. thread): def _ init _ (self, work_queue): super (). _ init _ () # self. work_queue = work_queue def run (self): num = 1 while True: self. work_queue.put (num) num = num + 1 time. sleep (1) # Pause for 1 second # A thread retrieves numbers from the queue and displays them to the terminal class Printer (threading. thread): def _ init _ (self, work_queue): super (). _ init _ () # self. work_queue = work_queue def run (self): while True: num = self. work_queue.get () # When the queue is empty, it will be blocked until there is data print (num) def main (): work_queue = queue. queue () producer = Producer (work_queue) producer. daemon = True # When the main thread exits, the sub-thread also exits the producer. start () printer = Printer (work_queue) printer. daemon = True # When the main thread exits, the sub-thread also exits printer. start () work_queue.join () # The main thread stops here until all numbers are get () and task_done (). Because task_done () is not called, it will be blocked, until the user presses ^ Cif _ name _ = '_ main _': main ()
The queue is thread-safe and does not need to be locked when accessed from multiple threads.
If work_queue.get () is called after work_queue.task_done (), work_queue.join () will return when the queue is empty.
Here, work_queue.put () is used to place objects in the queue at a certain time interval. If work_queue.task_done () is called, when the Number 1 is get () and the queue is empty, join () returns, the program is over.
That is, the program only prints 1 and then exits.
Therefore, in this scenario, you cannot call task_done (), and the program will keep repeating.