FrozenHeart
FrozenHeart

Reputation: 20746

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.

Upvotes: 2

Views: 319

Answers (1)

xaxxon
xaxxon

Reputation: 19761

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.

Upvotes: 4

Related Questions