InterviewSolution
| 1. |
How Can You Identify Different C++11 Threads? |
|
Answer» C++11 gives UNIQUE ids to forked threads which can be retrieved using : By calling the get_id() member function for a specific thread By calling std::this_thread::get_id() for the CURRENTLY executing thread An example of both is given below: #INCLUDE "stdafx.h" #include <string> #include <thread> #include <iostream> #include <functional> using namespace std; void Count() { for (int i = 0; i < 100; i++) { cout << "counter at: " << i << endl; } } int MAIN() { thread t22(Count); //Get the ID of the t22 thread std::thread::id k = t22.get_id(); cout << k << endl; //Get the ID of the MAIN Thread std::thread::id j = std::this_thread::get_id(); cout << j << endl; return 0; } If I run this code, I can see the thread ids in "threads" and "locals" window. Also note that the thread name is almost useless. However, the "Location" column can give an indication as to which thread is executing. C++11 gives unique ids to forked threads which can be retrieved using : By calling the get_id() member function for a specific thread By calling std::this_thread::get_id() for the currently executing thread An example of both is given below: #include "stdafx.h" #include <string> #include <thread> #include <iostream> #include <functional> using namespace std; void Count() { for (int i = 0; i < 100; i++) { cout << "counter at: " << i << endl; } } int main() { thread t22(Count); //Get the ID of the t22 thread std::thread::id k = t22.get_id(); cout << k << endl; //Get the ID of the MAIN Thread std::thread::id j = std::this_thread::get_id(); cout << j << endl; return 0; } If I run this code, I can see the thread ids in "threads" and "locals" window. Also note that the thread name is almost useless. However, the "Location" column can give an indication as to which thread is executing. |
|