Open In App

How to Detach a Thread in C++?

Last Updated : 20 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In C++, a thread is a basic element of multithreading that represents the smallest sequence of instructions that can be executed independently by the CPU. In this article, we will discuss how to detach a thread in C++.

What does Detaching a Thread mean?

Detaching a thread means allowing the thread to execute independently from the thread that created it. Once detached, the parent thread can continue its execution without waiting for the detached thread to finish. Detaching a thread is useful when you don’t need to synchronize with the thread or obtain its return value.

How to Detach a Thread in C++?

In C++, you can detach a thread by calling the detach() member function on an std::thread object. Once detached, the thread’s resources will be automatically released when it completes its execution.

Note: You should be careful while detaching a thread as the main thread may terminate before the thread completes its task.

C++ Program to Detach a Thread

C++
// C++ Program to illustrate how to detach a thread
#include <chrono>
#include <iostream>
#include <thread>
using namespace std;

void threadFunction()
{
    // Some work
    cout << "Detached thread executing..." << endl;
    this_thread::sleep_for(
        chrono::seconds(2)); // Simulate some work
    cout << "Detached thread completed." << endl;
}

// Driver Code
int main()
{
    thread detachedThread(threadFunction);
    // Detach the thread
    detachedThread.detach();
    // Main thread continues execution without waiting for
    // detachedThread
    cout << "Main thread continuing..." << endl;

    // Give some time for detached thread to complete
    this_thread::sleep_for(chrono::seconds(3));

    return 0;
}


Output:

Main thread continuing...
Detached thread executing...
Detached thread completed.

In this example, the detachedThread is created and detached using the detach() function. After detaching the thread, the main thread continues its execution without waiting for detachedThread to finish. The detached thread will execute independently and complete its work, printing the messages “Detached thread executing…” and “Detached thread completed.” before the program terminates.




Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads