Detached threads

If main() returns while some threads are still running, what happens? Does the process simply end, killing those threads, or does it continue running until all threads either terminate normally or kill each other?
I'm interested in the behavior of both Linux and BSD, but primarily Linux.
The detached attribute merely determines the behavior of the system when the thread terminates; it does not prevent the thread from being terminated if the process terminates using exit(3) (or equivalently, if the main thread returns).
https://man7.org/linux/man-pages/man3/pthread_detach.3.html
So, that's what the system may do, but what does it do?
exit_group - exit all threads in a process

Since glibc 2.3, this is the system call invoked when the _exit(2) wrapper function is called.
https://man7.org/linux/man-pages/man2/exit_group.2.html
I always assumed the process would just stop when the main thread terminates with detached threads running.

I think that's confirmed on Linux and FreeBSD with this code run with strace/truss.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <thread>
#include <chrono>
#include <iostream>
#include <atomic>

using namespace std::chrono_literals;

std::atomic<int> counter1{};

struct Global {
    ~Global() {
        std::cout << "~global: counter1 = " << counter1 << std::endl;
    }
};
Global global;

int main(int argc, char** argv) {
    std::thread dt1{[]() {
            while (true) {
                ++counter1;
                std::this_thread::sleep_for(800ns);
            }
        }};
    dt1.detach();

    std::this_thread::sleep_for(10s);
    std::cout << "counter1 = " << counter1 << std::endl;
}
What is the main difference between Detach and Join. I did a test, but I cannot see any different behavior for the thread. I am afraid about an eventually memory leak. Is there a significative difference?
Last edited on
join() blocks until the thread function returns. detach() detaches the OS thread from the std::thread object, letting the object be destructed independently of the state of the OS thread's state.
Thanks for the explanation. So using detach() without any object destruction, it generates a persistent memory leak?
> So using detach() without any object destruction, it generates a persistent memory leak?

No. std::thread::detach()
Separates the thread of execution from the thread object, allowing execution to continue independently.
Any allocated resources will be freed once the thread exits
https://en.cppreference.com/w/cpp/thread/thread/detach
Last edited on
The example on the cppref site is interesting. Thanks ++
Topic archived. No new replies allowed.