2

Is it ok to do the following?

#include <iostream>
#include <thread>

std::thread th;

void foo()
{
    std::cout << __func__ << std::endl;
    th = std::thread(foo);
}

int main()
{
    th = std::thread(foo);
    th.join();
}

gcc crashes -- http://coliru.stacked-crooked.com/a/3c926507ab0f8a5c.

I know that there's almost no need to do this but I want to know the answer just for academic purposes.

FrozenHeart
  • 19,844
  • 33
  • 126
  • 242
  • Seems to me at the very least there is a data race on `th`, since it is read in one thread and written in another without synchronisation. Which is realise is not quite what you are asking about. – BoBTFish Oct 07 '16 at 06:54

1 Answers1

4
th = std::thread(foo);

You're not joining on your thread.

http://en.cppreference.com/w/cpp/thread/thread

destructs the thread object, underlying thread must be joined or detached

As stated in comments on another answer, assignment has the same requirements as destruction, since the previous thread object is lost.

xaxxon
  • 19,189
  • 5
  • 50
  • 80
  • 1
    Yeah, and it also has UB because of the data race, right? – FrozenHeart Oct 07 '16 at 07:05
  • Yes, but the actual generated code can still be reasoned about. I'm not giving the code my blessing, but you have to be careful how much you nitpick a testcase -- you never know what's been taken out to get to a testcase. – xaxxon Oct 07 '16 at 07:06