Search code examples
c++multithreadingc++11waitproducer-consumer

How can I have a producer and consumer communicate both ways?


I would like to have a worker thread wait for a command, do it, and then send the result back to the caller. This differs from the regular producer/consumer problem because of the response back.

This is what I'm thinking:

main
{
construct workers
push to shared input buffers
notify workers
wait
print results from shared output buffer
}

worker
{
wait
read from shared input buffer
do work
notify main
}

Am I on the right track? Is there a chance that the worker could respond before main starts waiting?

(I'm using C++ if that is relevant)


Solution

  • You are on the right track, but you can simplify things a bit and eliminate the need to signal or wait for signal

    main
    {
        push to shared input buffers
        construct workers // create and immediately run. No need for signal
        while more workers
            join worker // will block until worker thread exits
        print results from shared output buffer
    }
    
    worker
    {
        read from shared input buffer
        do work
    }
    

    Depending on how you are partitioning the shared buffer, or not partitioning, you may need to protect it from concurrent writes.