python_ concurrent programming - pipes and data sharing

1. Pipeline

from multiprocessing Import Pipe 

, conn1,, conn2 = Pipe ()     # returns two values 
conn1.send ( ' WDC ' )    # send 
Print (conn2.recv ()) # receiving 
conn2.send ( ' YHF ' )
 Print (conn1.recv ( ))

Results: - two-way communication

 

2. transfer data in the process

from multiprocessing import Pipe,Process

class Pr1(Process):
    def __init__(self,conn1):
        super().__init__()
        self.conn1 = conn1
    def run(self):
        self.conn1.send('吃了吗?')

if __name__ == '__main__':
    conn1,conn2 = Pipe()
    p = Pr1(conn1)
    p.start()
    print(conn2.recv())

result:

 

 To solve the blocking problem when the pipeline is empty of data, continues to acquire data caused.

from multiprocessing Import Pipe, Process 

class Pr1 (Process):
     DEF  the __init__ (Self,, conn1,, conn2): 
        Super (). the __init__ () 
        self.conn1 = , conn1, 
        self.conn2 = conn2
     DEF RUN (Self): 
        self.conn2.close ()   # close conn2 
        the while True:
             the try :
                 Print (self.conn1.recv ())
             the except EOFError:     # when all else conn ports are closed, leaving only a port conn still get the data in the pipe, and the pipe inside was empty when EOFError error will be reported.
                self.conn1.close ()    # Close, conn1, 
                BREAK 

IF  the __name__ == ' __main__ ' : 
    , conn1,, conn2 = Pipe () 
    P = Pr1 (, conn1,, conn2) 
    p.start () 
    conn1.close ()    # Close, conn1, 
    for I in the Range (10 ): 
        conn2.send ( ' Have you eaten yet? ' ) 
    conn2.close ()   # close conn2

Result: The output data 10 times, then end all processes.

Guess you like

Origin www.cnblogs.com/wangdianchao/p/12079780.html