0

I'm having to use an API that uses Facebook Folly Executor library. Tasks (functions) are pushed into a queue, then threads in the thread pool run whatever available task.

But in case the pool only has 1 single thread, what happens? For example this case:

Global init: atomic<int> x = 0
Job 1: while(x != 1) {}
Push job 1 into thread pool queue
Job 2: x = 1;
Push job 2 into thread pool queue

When lauching 2 std::thread manually, the program works as expected and does not have any deadlock or undefined behavior. However, what happens in this case when these 2 jobs are pushed into a thread pool with only 1 thread? If it's concurrent then all is fine, but if jobs in the queue must be completed in the correct order then i'll deadlock.

Are there any general guidance on how a thread pool library should behave in this case?

Huy Le
  • 1,439
  • 4
  • 19
  • 3
    Thread pools are not a good match for threads that are dependent on each other. A thread pool is well-suited for when the "work" is truly independent. – Some programmer dude Sep 19 '22 at 08:25
  • Oh, it's a legacy API that I'm forced to work with. So that can't be changed unfortunately – Huy Le Sep 19 '22 at 08:27
  • If a task is running and it requires another task to have been run, its request to that result should make itself waiting, freeing the thread for instance of that requested task. Deadlock is an other matter, of wrong programming, a cyclic locking, no matter how many threads. – Joop Eggen Sep 19 '22 at 08:35
  • then do not split waiting for the flag and setting the flag into two tasks. Make it one task that is independent of other tasks. You can use the thread pool and then have a task spawn more threads if needed manually – 463035818_is_not_an_ai Sep 19 '22 at 08:35
  • a thread pool library cannot reliably detect such a situation. It is your responsibility to use tasks that can be executed – 463035818_is_not_an_ai Sep 19 '22 at 08:36
  • `a thread pool library cannot reliably detect such a situation` I guess this is the answer then. I just want to know how a thread pool designer treat this case. – Huy Le Sep 19 '22 at 08:40

0 Answers0