標籤:send cer notify main python open join() threading pytho
#練習:管道練習,雙工,單工,將受到的訊息儲存到檔案中import multiprocessing as mpfrom multiprocessing import Process,Lockdef write_file(content,lock,file_path="e:\\test40.txt"): lock.acquire() with open(file_path,"a+")as f1: f1.write(content+"\n") lock.release()def proc_1(pipe,lock): pipe.send("hello") write_file("hello",lock) print ‘proc_1 received: %s‘ %pipe.recv() pipe.send("what is your name?") write_file("what is your name?",lock) print ‘proc_1 received: %s‘ %pipe.recv()def proc_2(pipe,lock): print ‘proc_2 received: %s‘ %pipe.recv() pipe.send("hello,too") write_file(‘hello, too‘,lock) print ‘proc_2 received: %s‘ %pipe.recv() pipe.send("I don‘t tell you!") write_file("I don‘t tell you!",lock)if __name__=="__main__": lock=Lock() # 建立一個管道對象pipe pipe=mp.Pipe() print len(pipe) #元群組類型 print type(pipe) # 將第一個pipe對象傳給進程1 p1=mp.Process(target=proc_1,args=(pipe[0],lock)) # 將第二個pipe對象傳給進程2 p2=mp.Process(target=proc_2,args=(pipe[1],lock)) #這裡按理說應該是收的先啟起來,但這個例子裡p1和p2哪個先啟起來沒關係 p2.start() p1.start() p2.join() p1.join()#練習:condition,notify_all通知所有,這個例子裡,有可能出現消費者收到訊息較快,比生產者訊息先列印出來的情況,如果使用notify(),就需要有幾個進程就寫幾個notify()import multiprocessing as mpimport threadingimport timedef consumer(cond): with cond: print("consumer before wait") #等待消費 cond.wait() print("consumer after wait")def producer(cond): with cond: print("producer before notifyAll") # 通知消費者可以消費了 cond.notify_all() print("producer after notifyAll")if __name__=="__main__": condition=mp.Condition() p1=mp.Process(name="p1",target=consumer,args=(condition,)) p2=mp.Process(name="p2",target=consumer,args=(condition,)) p3=mp.Process(name="p3",target=producer,args=(condition,)) p1.start() time.sleep(2) p2.start() time.sleep(2) p3.start()
【Python】管道通訊和condition