Working with threads
When the C++ program starts – that is, the main()
function starts its execution – you can create and launch new threads that will run concurrently with the main thread. To start a thread in C++, you should declare a thread object and pass it the function that you want to run concurrently to the main thread. The following code demonstrates declaring and starting a thread using std::thread
, which is defined as follows:
#include<thread>#include <iostream> void foo() { std::cout << "Testing a thread in C++" << std::endl; } int main() { std::thread test_thread{foo}; }
That’s it. We can create a better example to show how two threads work concurrently. Let’s say we print numbers in a loop concurrently to see which thread prints what:
#include <thread>#include <iostream> void print_numbers_in_background() { auto ix...