Python3, open a thread, 1 seconds to write an incremented number to the queue, open a thread, remove the number from the queue, and print to the terminal
#! /usr/bin/env Python3 Import Time import threading Import Queue # A thread that, at intervals, writes an incremented number to the queue # Producer class Producer (Threadin G.thread): Def __init__ (self, Work_queue): Super (). __init__ () # must call Self.work_queue = Work_queue def ru N (self): num = 1 while True:self.work_queue.put (num) num = num+1 time.sleep (1) # pause 1 seconds # a thread, from The queue takes out the number and displays it to the Terminal class Printer (threading). Thread): Def __init__ (self, Work_queue): Super (). __init__ () # 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 # when the main thread exits, the child thread also exits Producer.start () printer = Printe R (work_queue) Printer.daemon = True # when the main thread exits, the child thread Exits Printer.start () Work_queue.join () # The main thread stops here until all the digits are get (), and Tas
K_done (), where Task_done () is not invoked, is blocked until the user presses ^c if __name__ = = ' __main__ ': Main ()
The queue is thread-safe and requires no locking when accessed from multiple threads.
If Work_queue.task_done () is called after Work_queue.get (), then Work_queue.join () returns when the queue is empty.
Here Work_queue.put () is a time interval to put things into the queue, if the call Work_queue.task_done (), after the number 1 is get (), the queue is empty, join () returned, the program is over.
That is, the program only prints 1 and then quits.
So in this use scenario, you can't call Task_done (), and the program will go through the loop.