Can i move ownership using std::move() from Thread T1 to T2 when T1 is executing func_1()
I am not sure whether this is the correct way or not? Some one say we shouldn’t move the ownership when thread is running. we should do it before running the thread.
Could you tell me what is the correct way and how to do it?
#include <iostream>
#include <thread>
#include <chrono>
void func_1()
{
while (true)
{
std::cout << "thread_id :" << std::this_thread::get_id() << std::endl;
int x = 0;
while (x < 2000)
{
std::cout << "x :" << x << std::endl;
x++;
}
break;
}
}
int main()
{
std::thread T1(func_1);
std::thread T2(std::move(T1));
T2.join();
}
>Solution :
Some one say we shouldn’t move the ownership when thread is running. we should do it before running the thread.
That’s simply wrong. There is no problem with moving the std::thread object while it manages a running thread. The move doesn’t affect the execution of the thread in any way. It just hands over management of the thread to the target std::thread object of the move.
Your shown code is fine and doesn’t behave in any way different than
std::thread T1(func_1);
T1.join();
in main would.
In fact, before the thread starts running a std::thread object can only either be in a default-constructed or moved-from state. Moving from such a state is completely pointless. So no idea why one would consider that as a use case.
Maybe this is a misunderstanding and what you heard was that you shouldn’t move a std::thread object into another std::thread object that already manages a running thread. That can’t work, because giving the target std::thread object management over the thread managed by the source std::thread object requires first giving up management of the thread that the target is already managing, i.e. if it is in a joinable state it must first be joined, just as required by the destructor of std::thread.