【Python】管道通信和condition

#练习:管道练习,双工,单工,将受到的消息保存到文件中
import multiprocessing as mp
from multiprocessing import Process,Lock

def write_file(content,lock,file_path="e:\test40.txt"):
    lock.acquire()
    with open(file_path,"a+")as f1:
        f1.write(content+"
")
    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 mp
import threading
import time

def 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()
原文地址:https://www.cnblogs.com/jingsheng99/p/8799294.html