dimanche 3 novembre 2019

Thread join() should not make the caller thread wait for *this, at least for multiple threads

According to cppreference.com, std::thread::join

Blocks the current thread until the thread identified by *this finishes its execution.

The way I understand this is that if we launch a thread, then join it e.g. from main, main will block till the thread finishes. However, if we have a thread pool, and run

for(auto& t: thread_pool)
    t.join();

I'd expect (according to the formulation of cppreference) that main will block until the first thread finishes. However this is not the case, as it can be seen here:

// example for thread::join
#include <iostream>       // std::cout
#include <thread>         // std::thread, std::this_thread::sleep_for
#include <chrono>         // std::chrono::seconds

void pause_thread(int n) 
{
  std::this_thread::sleep_for (std::chrono::seconds(n));
  std::cout << "pause of " << n << " seconds ended\n";
}

int main() 
{
  std::cout << "Spawning 3 threads...\n";
  std::thread t1 (pause_thread,1);
  std::thread t2 (pause_thread,2);
  std::thread t3 (pause_thread,3);
  std::cout << "Done spawning threads. Now waiting for them to join:\n";
  t3.join();
  t2.join();
  t1.join();
  std::cout << "All threads joined!\n";
}

where the output is

Spawning 3 threads...
Done spawning threads. Now waiting for them to join:
pause of 1 seconds ended
pause of 2 seconds ended
pause of 3 seconds ended
All threads joined!

so clearly main didn't block and wait for the first thread to finish (then second and so on).

Question: is join just preventing the *this thread from finishing earlier than the caller?

Aucun commentaire:

Enregistrer un commentaire