VOOZH about

URL: https://www.geeksforgeeks.org/cpp/how-to-detach-a-thread-in-cpp/

⇱ How to Detach a Thread in C++? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to Detach a Thread in C++?

Last Updated : 23 Jul, 2025

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 anstd::threadobject. 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


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.



Comment