【Python】管道通訊和condition

來源:互聯網
上載者:User

標籤: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

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.