0
void runner(int id, int a, int b) {...}

void caller()
{
  static ctpl::thread_pool pool(4);
  for (int i = 0; i < nbThreads; i++) {
    pool.push(runner, a, b);
  }
  pool.stop(true); // this kills all threads, meaning next time this function is called i have to create them again
}

So I'm using this library here: https://github.com/vit-vit/ctpl

However, in the example, I did not see any function to synchronize the threads. For std::thread, that would be th.join(). pool.get_thread(i).join() is not the solution; it freezes the because the thread is running always running to accept new commands, which is its intended behavior.

The only way I see that work is pool.stop(true). But if I do this, the threads are destroyed and I have to create them again next time, which defeats the point of a thread pool.

Can someone who use this library show me how to synchronize threads?

Huy Le
  • 825
  • 2
  • 11
  • have you read through this post: https://stackoverflow.com/questions/15752659/thread-pooling-in-c11 basically -- There is a difference between a "thread pool" and a collection of threads. I am thinking you want the latter. From the link: `A pool of threads means that all your threads are running, all the time – in other words, the thread function never returns.` – Andy Aug 01 '20 at 06:09
  • with the latter, i have to create new threads each time a function is called, which cost time. I'm looking for a way so that threads only need to be created once, then reuse – Huy Le Aug 01 '20 at 07:21
  • 1
    ??? why are you trying to stop/join the pool if you need it later? Just create it once, at program initialization, and then.....don't stop it! – Martin James Aug 02 '20 at 06:51

1 Answers1

0

Use std::future to get the result of each thread. Then use wait() on std::future objects.

std::future<void> results[nbThreads];
for (int i=0; i<nbThreads; i++) results[i] = pool.push(runner, a, b);
for (int i=0; i<nbThreads; i++) results[i].wait(); // synchronize all threads
Huy Le
  • 825
  • 2
  • 11