fork download
  1. #include <iostream>
  2. #include <thread>
  3. #include <map>
  4. #include <string>
  5. using namespace std;
  6.  
  7. std::map<std::thread::id, std::string> threadMap;
  8. std::thread::id threadId1;
  9.  
  10. void printThread(std::thread::id threadId) {
  11. if (threadMap.find(threadId) != threadMap.end()) {
  12. cout<<"Thread exist name is "<<threadMap[threadId]<<endl;
  13. } else {
  14. cout<<"Thread isn't exist"<<endl;
  15. }
  16. }
  17.  
  18. void executeThreads() {
  19. std::thread t1([](){
  20. threadMap.insert(std::pair<std::thread::id, std::string>(std::this_thread::get_id(), string("Thread1")));
  21. cout<<"Printing thread 1"<<endl;
  22. printThread(std::this_thread::get_id());
  23. threadId1 = std::this_thread::get_id();
  24. });
  25. cout<<"Joining T1 thread"<<endl;
  26. t1.join();
  27. cout<<"T1 joined thread"<<endl;
  28. std::thread t2([](){
  29. threadMap.insert(std::pair<std::thread::id, std::string>(std::this_thread::get_id(), string("Thread2")));
  30. cout<<"Printing thread 2"<<endl;
  31. printThread(std::this_thread::get_id());
  32. });
  33. cout<<"Joining T2 thread"<<endl;
  34. t2.join();
  35. cout<<"T2 joined thread"<<endl;
  36. }
  37.  
  38. int main() {
  39. executeThreads();
  40. cout<<"Checking if thread 1 ID still exist in map"<<endl;
  41. printThread(threadId1);
  42. cout<<"Checking if current thread exist in map"<<endl;
  43. printThread(std::this_thread::get_id());
  44. return 0;
  45. }
Success #stdin #stdout 0.01s 5420KB
stdin
Standard input is empty
stdout
Joining T1 thread
Printing thread 1
Thread exist name is Thread1
T1 joined thread
Joining T2 thread
Printing thread 2
Thread exist name is Thread1
T2 joined thread
Checking if thread 1 ID still exist in map
Thread exist name is Thread1
Checking if current thread exist in map
Thread isn't exist