Python provides a mechanism for communication between threads through the queue module, allowing threads to be divided into data.
Personal feeling that the queue is the concept of a tube
A producer consumer problem
1 fromRandomImportRandint2 fromThreadingImportThread3 fromQueueImportQueue4 fromTimeImportSleep5 6 7 defWriteq (queue):8 Print('starting put queue ...')9Queue.put ('hahaha', 1) #1表示在有可用空间前, blockingTen Print('size Now', Queue.qsize ()) One A - defREADQ (queue): - Print('starting get queue ...') theval = queue.get (1) #1表示在有可用元素前阻塞 - Print('consume from Queu...size now', Queue.qsize ()) - - + defwriter (queue, loops): - forIinchRange (loops): + Writeq (queue) ASleep (Randint (1, 3)) at - - defReader (queue, loops): - forIinchRange (loops): - READQ (queue) -Sleep (Randint (2, 5)) in - toFuncs =[writer, reader] + - the defMain (): *Nloops = Randint (2, 5) $Q = Queue (32)Panax Notoginseng -Threads = [] the forIinchRange (len (funcs)): +t = Thread (target=funcs[i], args=(q, nloops)) A threads.append (t) the + forIinchRange (len (funcs)): - Threads[i].start () $ $ forIinchRange (len (funcs)): - Threads[i].join () - the Print(' All done') - Wuyi if __name__=='__main__': theMain ()
Output Result:
"[email protected]" queue module-producer consumer issues