Question: Sometime I have to use `std::thread` to speed up my application. I also know `join()` waits until a thread completes. This is easy to understand, but what's the difference between calling `detach()` and not calling it?

I thought that without `detach()`, the thread's method will work using a thread independently.

Not detaching:

```
void Someclass::Somefunction() {
    //...

    std::thread t([ ] {
        printf("thread called without detach");
    });

    //some code here
}

```

Calling with detaching:

```
void Someclass::Somefunction() {
    //...

    std::thread t([ ] {
        printf("thread called with detach");
    });

    t.detach();

    //some code here
}

```

Answer: 
In the destructor of `std::thread`, `std::terminate` is called if:

* the thread was not joined (with `t.join()`)
* and was not detached either (with `t.detach()`)

Thus, you should always either `join` or `detach` a thread before the flows of execution reaches the destructor.

---

When a program terminates (ie, `main` returns) the remaining detached threads executing in the background are not waited upon; instead their execution is suspended and their thread-local objects destructed.

Crucially, this means that *the stack of those threads is not unwound* and thus some destructors are not executed. Depending on the actions those destructors were supposed to undertake, this might be as bad a situation as if the program had crashed or had been killed. Hopefully the OS will release the locks on files, etc... but you could have corrupted shared memory, half-written files, and the like.

---

So, should you use `join` or `detach` ?

* Use `join`
* Unless you need to have more flexibility AND are willing to provide a synchronization mechanism to wait for the thread completion *on your own*, in which case you may use `detach`
According to [cppreference.com](https://en.cppreference.com/w/cpp/thread/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.
> 
> 
> After calling detach `*this` no longer owns any thread.
> 
> 
> 

For example:

```
  std::thread my_thread([&](){XXXX});
  my_thread.detach();

```

Notice the local variable: `my_thread`, while the lifetime of `my_thread` is over, the destructor of `std::thread` will be called, and `std::terminate()` will be called within the destructor.

But if you use `detach()`, you should not use `my_thread` anymore, even if the lifetime of `my_thread` is over, nothing will happen to the new thread.