InterviewSolution
| 1. |
How Can You Create Background Tasks With C++11 Threads? |
|
Answer» You can MAKE a std::THREAD RUN in the background by calling std::thread::detach() on it. Once detached, a thread continues to run in the background and cannot be communicated with or waited upon to complete. When you detach a thread, the ownership and control passes over to the C++ Runtime LIBRARY, which ensures that the resources allocated to the thread are deallocated once the thread exits. Here's a contrived example. We have a Count() function that prints numbers 1 to 1000 on the screen. If we create a thread to run the function and detach the thread immediately, we'll not see any output – because the main thread terminates before the "Count" thread has had an opportunity to run. To see some of the output, we can put the main thread to sleep for 10 miliseconds which gives the "count" thread to send some of the output to the screen. #include "stdafx.h" #include #include #include #include using namespace std; void Count() { for (int i = 0; i < 100; i++) { cout << "counter at: " << i << endl; } } int main() { thread t1(Count); std::this_thread::sleep_for(std::chrono::milliseconds(10)); t1.detach(); return 0; } You can make a std::thread run in the background by calling std::thread::detach() on it. Once detached, a thread continues to run in the background and cannot be communicated with or waited upon to complete. When you detach a thread, the ownership and control passes over to the C++ Runtime Library, which ensures that the resources allocated to the thread are deallocated once the thread exits. Here's a contrived example. We have a Count() function that prints numbers 1 to 1000 on the screen. If we create a thread to run the function and detach the thread immediately, we'll not see any output – because the main thread terminates before the "Count" thread has had an opportunity to run. To see some of the output, we can put the main thread to sleep for 10 miliseconds which gives the "count" thread to send some of the output to the screen. #include "stdafx.h" #include #include #include #include using namespace std; void Count() { for (int i = 0; i < 100; i++) { cout << "counter at: " << i << endl; } } int main() { thread t1(Count); std::this_thread::sleep_for(std::chrono::milliseconds(10)); t1.detach(); return 0; } |
|