I'm working with a Thread Pool. So I'm looking for a simple and efficient way to notify the father that a child has finished its job and that it's ready to work on another. Is there a way to do this?
The use of Condition Variable is only half-duplex (from father to child(s)) and the use of signals is totally NOT recommended.
What you suggest?
Thanks in advance.
Best How To :
I think you're solving the problem other way round, unless you don't want to implement something like the Leader/Follower pattern, in which the threads take turns being leaders. This looks good on paper, but I've found it rarely to be efficient for ephemeral tasks due to the amount of locking required. Using
signalfd or other form of waiting is also not exactly great due to the context switching. To sum it up, define efficient in order to propose a correct solution.
The simple thread-pool pattern can get away with just greedy consumers and no child-to-parent notification.
task = wait_input()
task = pop_queue(q)
Depending on your implementation, the
signal_workers() can be analogous to
pthread_cond_signal to wake up any thread, the queue locking must be blocking. This way the clients will either wait on the lock or process tasks. If you want to terminate them, you should set a flag, and broadcast them. You can also use read/write locks and synchronize on the condition. TL;DR, you should use locked queue instead of parent distributing jobs on-demand.
Once again, you should use a locking strategy based on your workload. It's a very different task to coordinate long-running jobs on something like SLURM, where child-parent notification is a good idea, and a thread pool where it is not.