码迷,mamicode.com
首页 > 编程语言 > 详细

【Python】管道通信和condition

时间:2018-04-12 00:12:23      阅读:251      评论:0      收藏:0      [点我收藏+]

标签:send   cer   notify   main   python   open   join()   threading   pytho   

#练习:管道练习,双工,单工,将受到的消息保存到文件中
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+"\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 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()

 

【Python】管道通信和condition

标签:send   cer   notify   main   python   open   join()   threading   pytho   

原文地址:https://www.cnblogs.com/jingsheng99/p/8799294.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!