Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++11 std::thread::detach and access to shared data

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?

like image 862
Matthew Hoggan Avatar asked Jan 03 '13 22:01

Matthew Hoggan


2 Answers

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:

  • Declare the int somewhere that will not go out of scope during the lifetime of any threads that need it (perhaps a global).
  • Declare shared data as a std::shared_ptr and pass that by value into the thread.
  • Pass by value (performing a copy) into the thread.
  • Pass by rvalue reference (performing a move) into the thread.
like image 51
Sean Cline Avatar answered Oct 15 '22 00:10

Sean Cline


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.

like image 30
David Schwartz Avatar answered Oct 15 '22 01:10

David Schwartz