• 【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()
  • 相关阅读:
    ASP.NET 表单验证 Part.2(实现表单验证)
    长工的买房故事
    软件界面交互和易用性改进总结[zz]
    访问hotmail邮箱的途径
    Google内部收集员工创意的方法[转载]
    Web2.0地图展望
    C++开源跨平台类库集
    庆祝lucky荣登早教网首页宝宝
    在那些打磨汉芯的日子里[转贴]
    在中国搞技术只能混碗饭吃,没有太大希望
  • 原文地址:https://www.cnblogs.com/jingsheng99/p/8799294.html
Copyright © 2020-2023  润新知