The detach
function prevents an exception from being thrown when the thread
object goes out of scope. Usually, you would want to call join
but if you don't want to block the execution you need to call detach
. However, you probably need to use another synchronization mechanism to make sure everything is fine if the thread
is still running when main
is ready to exit. See the following contrived example.
Example Code
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <iostream>
#include <mutex>
#include <string>
#include <thread>
std::mutex mu;
std::condition_variable cv;
bool finished = false;
void threadFunc()
{
for (int i = 0; i < 5; ++i)
{
std::this_thread::sleep_for(std::chrono::milliseconds(1));
std::unique_lock<std::mutex> lock(mu);
std:: cout << "Thread: " << (0 - i) << "\n";
}
std::unique_lock<std::mutex> lock(mu);
finished = true;
cv.notify_one();
}
int main()
{
{
std::thread t1(threadFunc);
t1.detach(); // Call `detach` to prevent blocking this thread
} // Need to call `join` or `detach` before `thread` goes out of scope
for (int i = 0; i < 5; ++i)
{
std::unique_lock<std::mutex> lock(mu);
std::cout << "Main: " << i << "\n";
}
std::cout << "End of Main\n";
std::unique_lock<std::mutex> lock(mu);
cv.wait(lock, [&finished]() { return finished; });
return 0;
}
Example Output
Main: 0
Main: 1
Main: 2
Main: 3
Main: 4
End of Main
Thread: 0
Thread: -1
Thread: -2
Thread: -3
Thread: -4
Live Example
Again, the above is a contrived example and in your case you could more easily use join
instead of detach
before allowing main
to return.