ar2015
ar2015

Reputation: 6150

How does thread join work?

I found a C++ web server example which works based on threads.

I replaced line 161 from

server_thread.join();

to

std::cout<<"Before thread join\n";

server_thread.join();

std::cout<<"5 sec delay starting ...\n";
this_thread::sleep_for(chrono::seconds(5));
std::cout<<"5 sec delay ended\n";

The result obviously shows that the code after join is not running.

123
{"firstName": "John","lastName": "Smith","age": 25}
John Smith
Before thread join

While in my simple example below, the code below thread_2.join(); runs as well. While it does not run final std::cout until both threads are released. What is the logic behind .join(); does it pause the current thread?

If I want the code after server_thread.join(); continues running alongside with the server, what is the proper solution?

main.cpp

#include <boost/thread.hpp>
#include <iostream>
#include <thread>

void task1() { 
    // do stuff
    for(int i=0;i<10;i++)
    {
        std::cout<<"task1 "<<"["<<i<<"]\n";
        std::this_thread::sleep_for(std::chrono::seconds(1));
    }
}

void task2()
{ 
    for(int i=0;i<10;i++)
    {
        std::cout<<"task2 "<<"["<<i<<"]\n";
        std::this_thread::sleep_for(std::chrono::seconds(1));
    }
}

int main ()
{
    using namespace boost; 
    std::thread thread_1 = std::thread(task1);
    std::thread thread_2 = std::thread(task2);

    // do other stuff
    thread_2.join();
    thread_1.join();
    // std::this_thread::sleep_for(std::chrono::seconds(10));
    std::cout<<"end of main function\n";
    return 0;
}

results:

task1 [0]
task2 [0]
task1 [1]
task2 [1]
task1 [2]
task2 [2]
task1 [task2 [33]
]
task2 [4]
task1 [4]
task2 [5]
task1 [5]
task2 task1 [[66]
]
task2 [task1 [77]
]
task2 task1 [[88]
]
task2 [9]
task1 [9]
end of main function

Upvotes: 2

Views: 2658

Answers (1)

ruakh
ruakh

Reputation: 183554

thread::join waits until the thread has completed.

In your first example, server_thread keeps running more-or-less indefinitely; the purpose of the join is to keep the main method from returning prematurely (since that would kill the server thread).

In your second example, the thread just does a quick task and then closes, so the join returns quickly.

Upvotes: 2

Related Questions