Hi all,
In this following piece of code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
|
#include <iostream>
#include <thread>
static bool finished = false;
void doWork(int n) {
using namespace std::literals::chrono_literals;
std::cout << " Worker thread id: " << std::this_thread::get_id() <<'\n';
while (!finished) {
std::cout << " Working ..." << n << '\n';
std::this_thread::sleep_for(1s);
}
}
int main()
{
std::thread worker(doWork, 8); // "doWork" is a pointer to the fucntion "doWork()"
std::cin.get();
finished = true;
worker.join();
std::cout << " main thread id: " << std::this_thread::get_id() << '\n';
std::cin.get();
return 0;
}
|
Is my understanding right?
The program starts from the main thread which is actually the
main() function, then the second thread,
worker, starts running and doing what for which is defined, while the main thread, too, is running at the same time, waiting for a character to get via
std::cin.get()
. Now we have two/multi threads working in parallel.
When we give
std::cin()
, a character, then the main thread proceeds to setting the bool variable,
finished, to true. At that point, the second thread, which has been running alongside the main thread, stops, exiting the loop and finishing its task.
The
worker.jopin()
makes sure that the main thread can't go further this line until the worker thread has finished its job. By having the second/worker exit, the main thread is allowed to step further to
std::cout...
and then the rest of the code until return.