Inter-process communication
Reference blog: http://blog.csdn.net/HeatDeath/article/details/72844120
I. Preface
A thread exists in a process. For threads in the same process, resources in the process are shared, and each thread can compete to obtain resources. Different processes have independent memory space and cannot directly access each other. How can processes communicate with each other?
2. inter-process communication 2.1 Queue ()
There is a queue in the thread, which is typically used in the producer and consumer models. While Queue () is used for inter-process communication, which is similar to the thread queue.
From multiprocessing import Process, Queueimport osimport timeimport random # code for writing data Process execution: def write (x): print ('process to write: % s' % OS. getpid () for value in ['A', 'B', 'C']: print ('put % s to queue... '% value) x. put (value) time. sleep (random. random () # code executed by the read data Process: def read (x): print ('process to read: % s' % OS. getpid () while True: value = x. get () print ('get % s from queue. '% value) if _ name _ =' _ main _ ': # The parent process creates a Queue and sends it to each sub-process: q = Queue () pw = Process (target = write, args = (q,) pr = Process (target = read, args = (q,) # promoter Process pw, write: pw. start () # promoter process pr, read: pr. start () # Wait for the completion of pw: pw. join () # in the pr process is an endless loop and cannot wait until it ends. It can only be forcibly terminated: pr. terminate ()2.2 Pipe ()
The Pipe () function returns a pair of connection objects connected by pipelines. The default value is duplex (bidirectional ).
The two connection objects returned by Pipe () represent the two ends of the pipeline. Each connection object has the send () and recv () methods (and so on)
Rom multiprocessing import Process, Pipedef f (conn): conn. send ([1, 2, 3]) # send while True: print ('receive from parent process: ', conn. recv () # The child process receives if _ name _ = '_ main _': parent_conn, child_conn = Pipe () # define the connection object p = Process (target = f, args = (child_conn,) p. start () print ('receive from child process: ', parent_conn.recv () parent_conn.send ('20140901') p. terminate () # output receive from child process: [1, 2, 3] receive from parent process: 123