Producer Consumer Model
fromMultiprocessingImportProcess,queueImportTime,randomdefproducer (name,q): forIinchRange (1,11): Ret="swill%s"%i q.put (ret)Print("Chef%s has produced%s"%(name, ret)) Time.sleep (random.randint (0,2))defCustomer (NAME,Q): whileTrue:ret=Q.get ()ifRET ==none: BreakTime.sleep (Random.randint (The)) Print("customer%s ate%s"%(Name,ret))if __name__=='__main__': Q=Queue () p= Process (target=producer,args= ("Egon", Q)) C= Process (target=customer,args= ("Alex", Q)) P.start () C.start () P.join () q.put (None) c.join ()Print("Main Process")
based on process
fromThreadingImportThread,current_threadImportQueueImportTime,randomdefproducer (name,q): forIinchRange (1,11): Ret="swill%s"%i q.put (ret)Print("Chef%s has produced%s"%(name, ret), Current_thread (). GetName ()) Time.sleep (random.randint (0,2))defCustomer (NAME,Q): whileTrue:ret=Q.get ()ifRET ==none: BreakTime.sleep (Random.randint (The)) Print("customer%s ate%s"%(Name,ret), Current_thread (). GetName ())if __name__=='__main__': Q=queue. Queue () P= Thread (target=producer,args= ("Egon", Q)) C= Thread (target=customer,args= ("Alex", Q)) P.start () C.start () P.join () q.put (None) c.join ()Print("Main Thread")
Thread-based
fromGeventImportMonkey;monkey.patch_all ()ImportgeventImportQueueImportThreadingImportTime,randomdefproducer (name,q): forIinchRange (1,11): Ret="swill%s"%i q.put (ret)Print("Chef%s has produced%s"%(name, ret), Threading.current_thread (). GetName ()) Time.sleep (random.randint (0,2))defCustomer (NAME,Q): whileTrue:ret=Q.get ()ifRET ==none: BreakTime.sleep (Random.randint (The)) Print("customer%s ate%s"%(Name,ret), Threading.current_thread (). GetName ())if __name__=='__main__': Q=queue. Queue () G1= Gevent.spawn (producer,"Egon", q) G2= Gevent.spawn (Customer,"Alex", Q) g1.join () q.put (None) g2.join ()Print("Main Thread", Threading.current_thread (). GetName ())
implementing concurrency on a single thread
Producer consumer model----------based on multi-process, multi-threading, single-threaded concurrency