mercredi 19 août 2020

Moving a thread to another thread while both threads are in use

// threadMovedFixed.cpp

#include <iostream> 
#include <thread> 
#include <utility>

int main(){ 

  std::thread t([]{std::cout << std::this_thread::get_id() << std::endl;}); 
  std::thread t2([]{std::cout << std::this_thread::get_id() << std::endl;}); 
  
  t.join();
  t = std::move(t2); 
  t.join(); 
  
  std::cout << "\n";
  std::cout << std::boolalpha << "t2.joinable(): " << t2.joinable() << std::endl;

}

I am looking at the following snippet, and it seems there are several issues here.

(1) t2 is being moved to t while t2 while it may be in the middle of executing its lambda. What happens to t2 in this case? Does t2 terminate right away and t re-executes t2's lambda from the the beginning, or does it pick up where t2 left off?

(2) t is receiving t2, but t could be in the middle of its execution of the lambda. What happens here? Does t terminate its own call immediately upon receiving t2?

Aucun commentaire:

Enregistrer un commentaire