Another interesting case for transferring ownership from one thread to another, however, one thread cannot be assigned to another.
Strange, right? Yes, thread ownership may only be transferred from one thread to another, and the transfer must be requested explicitly by calling std::move ().
The example below explains how to use std::move to transfer ownership of a dynamic object into a thread.
The next question is, what if ownership is transferred to an already-owning thread? The answer is a runtime error since a thread cannot transfer ownership to another thread object that already owns it.
For a better understanding, I have outlined both scenarios in the example below.
#include <iostream>
#include <thread>
void cpp_thread_func_1()
{
std::cout << "This is a function 1" << std::endl;
}
void cpp_thread_func_2()
{
std::cout << "This is a function 2"<<std::endl;
}
int main()
{
std::thread thread_1(cpp_thread_func_1);
//Compile Error:: try to assigne one thread to another
//std::thread thread_2 = thread_1;
//move one thread form another
std::thread thread_2 = std::move(thread_1);
//OK:: implicit call to move constructor, as thread_1 doesn't own an object.
thread_1 = std::thread(cpp_thread_func_2);
std::thread thread_3 = std::move(thread_2);
//Runtime Error: thread_1 already owning thread object
//thread_1 = std::move(thread_3);
thread_1.join();
thread_3.join();
}