Python3, open a thread, interval 1 seconds to write an incremented number to the queue, then open a thread, remove the number from the queue and print to the terminal
The code is as follows:
#! /usr/bin/env Python3
Import time
Import threading
Import queue
# A thread that is spaced for a certain amount of time and writes an incremented number to the queue
# Producers
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 seconds
# A thread that takes a number out of the queue and displays it 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 blocks until there is data
Print (num)
def main ():
Work_queue = queue. Queue ()
Producer = producer (Work_queue)
Producer.daemon = True # Child threads also exit when the main thread exits
Producer.start ()
Printer = printer (work_queue)
Printer.daemon = True # Child threads also exit when the main thread exits
Printer.start ()
Work_queue.join () # The main thread will stop here until all the numbers are get (), and Task_done (), because there is no call to Task_done (), where it will remain 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.task_done () is called after Work_queue.get (), then Work_queue.join () is returned when the queue is empty.
Here Work_queue.put () is a time interval before putting things in the queue, if called Work_queue.task_done (), after the number 1 is get (), the queue is empty, the join () is returned, the program is finished.
That is, the program only prints 1 and then exits.
So in this usage scenario, task_done () cannot be called, and the program will continue to loop.
Https://docs.python.org/3/library/queue.html