mercredi 14 avril 2021

C++ thread pooling with function that adds new tasks recursively and dynamically

Here is a function which recursively generates tasks and a thread pool is used to perform these tasks.

ThreadPool pool{1};  // only one thread in the thread pool
std::function<void(int)> func;
func = [&](int x) -> void {
  if (x <= 0) return ;
  std::cout << x << std::endl;
  pool.AddTask(func, x - 1).get();  // AddTask() returns a std::future object
};
pool.AddTask(func, 5).get();

I tried several c++ thread pool libraries on the code but all get stuck (deadlock). The reason of the deadlock is that there is only one thread and the thread will get stuck at func(5) without return. I'd like to ask how to make the above lambda function work well using limited number of threads? In general, if we allow new tasks to be dynamically generated within a task, how can we make use of thread pool to achieve parallelism?

Aucun commentaire:

Enregistrer un commentaire