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