Multi Thread running after join

Ref: http://www.cplusplus.com/reference/thread/thread/join/

In below code, what I expect is t2 should print "pause of 2 seconds ended" in 2 seconds after t1 print, t3 should print in 3 seconds after t2 print and so on.
But the result seems t2 print in one second after t1 print, t3 print in 1 second after t2 print, that means each thread runs parallel.

To my understanding about function join's use case, when t1 is joined, it will block the thread of execution using the function pause_thread(int n), so t2 should not be executed until t1 completed, therefore t2 should print in 2 seconds after t1 print. Can you explain the reason? Thanks!

// 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 6 threads...\n";
std::thread t1(pause_thread, 1);
std::thread t2(pause_thread, 2);
std::thread t3(pause_thread, 3);
std::thread t4(pause_thread, 4);
std::thread t5(pause_thread, 5);
std::thread t6(pause_thread, 6);
std::cout << "Done spawning threads. Now waiting for them to join:\n";
t1.join();
t2.join();
t3.join();
t4.join();
t5.join();
t6.join();
std::cout << "All threads joined!\n";

return 0;
}
join just means: Don't go any further in this thread until the thread we called join on has completed. It does not mean other threads cease execution.
... what I expect is t2 should print "pause of 2 seconds ended" in 2 seconds after t1 print, t3 should print in 3 seconds after t2 print and so on.

std::future<> with a deferred launch policy will give you that effect:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream> // std::cout
#include <thread> // std::thread, std::this_thread::sleep_for
#include <chrono> // std::chrono::seconds
#include <future>

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

int main()
{
std::cout << "Spawning 6 threads...\n";
auto t1 = std::async(std::launch::deferred, pause_thread, 1);
auto t2 = std::async(std::launch::deferred, pause_thread, 2);
auto t3 = std::async(std::launch::deferred, pause_thread, 3);
auto t4 = std::async(std::launch::deferred, pause_thread, 4);
auto t5 = std::async(std::launch::deferred, pause_thread, 5);
auto t6 = std::async(std::launch::deferred, pause_thread, 6);
std::cout << "Done spawning threads. Now waiting for them to join:\n";
t1.get();
t2.get();
t3.get();
t4.get();
t5.get();
t6.get();
std::cout << "All threads joined!\n";

return 0;
}

edit: above auto == std::future<void> FYI
Last edited on
Topic archived. No new replies allowed.