Python multi-thread and queue operation instances, python multi-thread queue
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.
Copy codeThe Code is as follows:
#! /Usr/bin/env python3
Import time
Import threading
Import 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 _ () # Must be called
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 _ () # Must be called
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.
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 ^ C
If _ 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.
Https://docs.python.org/3/library/queue.html