jeudi 23 décembre 2021

Is there a performance benefit in using a pool of threads over simply creating threads?

I was wondering is there are performance benefits to using a pool of threads over simply creating threads and allowing the OS to queue and schedule them.

Say I have 20 available threads and I have 60 tasks I want to run on these threads, say I have something like;

void someTask() {

  //...performs some task

}

// say std::thread::hardware_concurrency() = 20

std::vector<std::thread> threads;
for (int i = 0; i < 60; i++) {
  threads.push_back(std::thread(someFunc);
}

std::for_each(threads.begin(),threads.end(),[](std::thread& x){x.join();});

Is there a benefit to instead creating a pool with 20 threads and giving each of these another 'task' when a thread becomes free? I assume that there is some overhead in spawning a thread, but are there other benefits to creating a pool for such a problem?

Aucun commentaire:

Enregistrer un commentaire