0

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)

Josh
  • 313
  • 3
  • 9
  • 2
    You have a thread that runs up until a condition is met. Then it notifies thread 2 and stops running. Thread 2 wakes, runs, meets a condition, notifies thread 1, and stops. Thread 1 wakes and runs. All of the work is serialized. You have eliminated the need for threading, and are better off with a single threaded [state machine](https://en.wikipedia.org/wiki/Finite-state_machine). – user4581301 Jul 19 '16 at 23:57
  • @user4581301 My plan is to have multiple workers so I can do the work in parallel. (I updated the post) – Josh Jul 20 '16 at 00:03
  • Are the workers ever expected to restart or will you create new threads if needed? – user4581301 Jul 20 '16 at 00:04
  • @user4581301 I will make new ones if needed. I plan to have the worker terminate forever when done. – Josh Jul 20 '16 at 00:06

1 Answers1

2

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.

user4581301
  • 33,082
  • 7
  • 33
  • 54