Home > Software design >  How to see if a pipe is empty python multiprocessing
How to see if a pipe is empty python multiprocessing

Time:07-23

I have 2 pipes in which i am sending data from other process.
I have a show_image function which is taking the output of both pipes.

pre_out_1, pre_in_1 = Pipe()
pre_out_2, pre_in_2 = Pipe()

p4 = multiprocessing.Process(target=Show_image, args=(pre_out_1,pre_out_2,))
p4.start

The idea is that i want to show the image which is available e.g if the image in pre_out_1 is not ready but the image in pre_out_2 is ready/available then show it. so, as soon as any one of them is available then that image should be shown without waiting for the other to be available.

This is what i did so far

def Show_image(pre_out_1,pre_out_2):
    while True:

        avail_1 = pre_out_1.poll()
        avail_2 = pre_out_2.poll()

        print(avail_1,avail_2)

But i am always getting false for both avail_1 and avail_2 even when the output is ready.

CodePudding user response:

The solution is to use the multiprocessing.connection.wait function, which can be passed a list of connection instances and returns a list of those which have data available:

import multiprocessing

def Show_image(pre_out_1, pre_out_2):
    try_number = 0
    while True:
        try_number  = 1
        ready_connections = multiprocessing.connection.wait([pre_out_1, pre_out_2])
        if pre_out_1 in ready_connections:
            item = pre_out_1.recv()
            print(f'Got from connection pre_out_1 item {item} on try #{try_number}')
        if pre_out_2 in ready_connections:
            item = pre_out_2.recv()
            print(f'Got from connection pre_out_2 item {item} on try #{try_number}')

if __name__ == '__main__':
    import time

    pre_out_1, pre_in_1 = multiprocessing.Pipe()
    pre_out_2, pre_in_2 = multiprocessing.Pipe()

    # Make child process a daemon process sothat we can terminate:
    p4 = multiprocessing.Process(target=Show_image, args=(pre_out_1, pre_out_2), daemon=True)
    p4.start()
    pre_in_1.send(1)
    time.sleep(1)
    pre_in_2.send(2)
    time.sleep(1)
    pre_in_1.send(3)
    pre_in_2.send(4)
    time.sleep(1) # allow Show_image to receive everything

Prints:

Got from connection pre_out_1 item 1 on try #1
Got from connection pre_out_2 item 2 on try #2
Got from connection pre_out_1 item 3 on try #3
Got from connection pre_out_2 item 4 on try #3
  • Related