вторник, 2 января 2024 г.

С++17: автоопределение в runtime потока вызова для функции

 #include <iostream>  
 #include <thread>  
   
 void foo(unsigned char *data)  
 {  
   thread_local std::thread::id currentId(std::this_thread::get_id());  
   
   static std::thread::id id1(std::this_thread::get_id());  
   if (currentId == id1)  
   {   
     std::cout << "Thread1" << std::endl;  
     return;  
   }  
   
   static std::thread::id id2(std::this_thread::get_id());  
   if (currentId == id2)  
   {   
     std::cout << "Thread2" << std::endl;  
     return;  
   }  
   
   throw std::runtime_error("Thread is not processed!");  
 }  
   
 int main()  
 {  
   unsigned char *ptr;  
     
   std::thread thread1([&] { foo(ptr); });  
   std::thread thread2([&] { foo(ptr); });  
   //std::thread thread3([&] { foo(ptr); });  // will be an exception
   
   thread1.join();  
   thread2.join();  
   //thread3.join();  
   
   return 0;  
 }  

Комментариев нет:

Отправить комментарий