FrozenHeart FrozenHeart - 2 months ago 7
C++ Question

Is it ok to move assign std::thread object from the same thread

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.

Answer
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.