I have a parent process which spawns a certain number of child processes. Those child processes do some work and send the parent a message with the results via a interprocess message queue. However, I would also like the child processes to wait for the parent process to send them an acknowledgement that the message has been properly received and processed, and terminate only after receiving such a signal from the parent.
Right now, the code looks more or less like this :
parent child
spawn process
wait for message do processing
send message
receive message wait on condvar
save the message
notify the condvar resume execution
wait for child termination terminate
Which, of course, leads to a deadlock if the parent does the notify on the condvar before the child even begins to wait on it – if that happens, then the parent waits for the child to exit, and the child waits for a signal on the condition variable.
So, my question is : how to ensure that the child always executes wait in the first place, that is before the parent executes notify? Or am I going about the whole problem completely wrong?
Thank you in advance.
Use an inter-process named semaphore or event – something that holds state, so that even if the parent signals before the child is waiting, the signal will still be received.