Python simple inter-thread communication

Source: Internet
Author: User

This section focuses on a simple example of inter-threading communication, using a thread-safe data structure for the queue. Queue saves the content of inter-thread communication,

ImportQueue fromThreadingImportThread fromRandomImportRandintclassWritethread (Thread):def __init__(self,sid,queue): Thread.__init__(self) self.sid=Sid Self.queue=QueuedefRun (self): Data= [Randint (1,10) for_inchRange (0,5)] Self.queue.put ((self.sid,data) )#--Here's the main point, put the thread number and data together as a tuple into the queue, or you'll be prompted for an integeris not an iterative objectclassReadthread (Thread):def __init__(self,queue): Thread.__init__(self) self.queue=QueuedefRun (self): whileTrue:sid, Data=Self.queue.get ()Print("Data read from thread {0},data is {1}". Format (sid,data)) Q=queue. Queue () Wthread= [Writethread (i, Q) forIinchRange (0,5)]rthread=Readthread (q) forTinchWthread:t.start () Rthread.start ( )

Python simple inter-thread communication

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.