C++ Thread Library - Function detach



Description

It returns when the thread execution has completed.

Declaration

Following is the declaration for std::thread::detach 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::detach.

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

void independentThread() {
   std::cout << "Starting thread.\n";
   std::this_thread::sleep_for(std::chrono::seconds(2));
   std::cout << "Exiting previous thread.\n";
}

void threadCaller() {
   std::cout << "Starting thread caller.\n";
   std::thread t(independentThread);
   t.detach();
   std::this_thread::sleep_for(std::chrono::seconds(1));
   std::cout << "Exiting thread caller.\n";
}

int main() {
   threadCaller();
   std::this_thread::sleep_for(std::chrono::seconds(5));
}

The output should be like this −

Starting thread caller.
Starting thread.
Exiting thread caller.
Exiting previous thread.
thread.htm
Advertisements