How to do it...

Here is a simple example of pipes. We have one process pipe that outputs numbers from 0 to 9, and a second process pipe that takes the numbers and squares them:

  1. Let's import the multiprocessing library:
import multiprocessing

  1. The pipe function returns a pair of connection objects connected by a two-way pipe. In the example, out_pipe contains the numbers from 0 to 9, which were generated by the target function of create_items:
def create_items(pipe):
output_pipe, _ = pipe
for item in range(10):
output_pipe.send(item)
output_pipe.close()
  1. The multiply_items function is based on two pipes, pipe_1 and pipe_2:
 def multiply_items(pipe_1, pipe_2):
close, input_pipe = pipe_1
close.close()
output_pipe, _ = pipe_2
try:
while True:
item = input_pipe.recv()
  1. This function returns the product of the elements of each pipe:
           output_pipe.send(item * item)
except EOFError:
output_pipe.close()
  1. In the main program,  pipe_1, and pipe_2 are defined:
if __name__== '__main__':
  1. First, process pipe_1 with numbers from 0 to 9:
    pipe_1 = multiprocessing.Pipe(True)
process_pipe_1 =
multiprocessing.Process
(target=create_items, args=(pipe_1,))
process_pipe_1.start()
  1. Then, process pipe_2, which picks up the numbers from pipe_1 and squares them:
    pipe_2 = multiprocessing.Pipe(True)
process_pipe_2 =
multiprocessing.Process
(target=multiply_items, args=(pipe_1, pipe_2,))
process_pipe_2.start()

  1. Close the processes:
    pipe_1[0].close()
pipe_2[0].close()
  1. Print out the results:
    try:
while True:
print (pipe_2[1].recv())
except EOFError:
print("End")
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.224.39.32