Python3 example of multithreaded programming in a _python

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.