The first step of writing multithreaded code is to spawn a thread. At this point, we must note that the application is already running an active thread, the main thread. So when we spawn a thread, there will be two active threads in the application.
To work through this recipe, you will need a machine running Windows and Visual Studio. No other prerequisites are required.
In this recipe, we will see how easy it is to spawn a thread. Add a source file called Source.cpp
and add the following code to it:
int ThreadOne() { std::cout << "I am thread 1" << std::endl; return 0; } int main() { std::thread T1(ThreadOne); if (T1.joinable()) // Check if can be joined to the main thread T1.join(); // Main thread waits for this to finish _getch(); return 0; }