C++ Thread Library - Function join



Description

It returns when the thread execution has completed.

Declaration

Following is the declaration for std::thread::join function.

void join();

C++11

void join();

Parameters

none

Return Value

none

Exceptions

No-throw guarantee − never throws exceptions.

Data races

The object is accessed.

Example

In below example for std::thread::join.

#include <iostream>
#include <thread>
#include <chrono>

void foo() {
   std::this_thread::sleep_for(std::chrono::seconds(1));
}

void bar() {
   std::this_thread::sleep_for(std::chrono::seconds(1));
}

int main() {
   std::cout << "starting helper...\n";
   std::thread helper1(foo);

   std::cout << "starting another helper...\n";
   std::thread helper2(bar);

   std::cout << "waiting for helpers to finish..." << std::endl;
   helper1.join();
   helper2.join();

   std::cout << "done!\n";
}

The output should be like this −

starting helper...
starting another helper...
waiting for helpers to finish...
done!
thread.htm
Advertisements