If you have shared variables between a std::thread
and the main thread (or any other thread for that matter), can you still access those shared variables even if you execute the thread::detach()
method immediately after creating the thread?
Yes! Global, captured and passed-in variables are still accessible after calling detach()
.
However, if you are calling detach, it is likely that you want to return from the function that created the thread, allowing the thread object to go out of scope. If that is the case, you will have to take care that none of the locals of that function were passed to the thread either by reference or through a pointer.
You can think of detach()
as a declaration that the thread does not need anything local to the creating thread.
In the following example, a thread keeps accessing an int
on the stack of the starting thread after it has gone out of scope. This is undefined behaviour!
void start_thread()
{
int someInt = 5;
std::thread t([&]() {
while (true)
{
// Will print someInt (5) repeatedly until we return. Then,
// undefined behavior!
std::cout << someInt << std::endl;
}
});
t.detach();
}
Here are some possible ways to keep the rug from being swept out from under your thread:
int
somewhere that will not go out of scope during the lifetime of any threads that need it (perhaps a global).std::shared_ptr
and pass that by value into the thread.Yes. Detaching a thread just means that it cleans up after itself when it is finished and you no longer need to, nor are you allowed to, join
it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With