Concurrency in games – creating a thread
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.
Getting ready
To work through this recipe, you will need a machine running Windows and Visual Studio. No other prerequisites are required.
How to do it…
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;
}How it works…
The first step is to include the header file, thread.h. This gives us access to all the inbuilt libraries that we may need to create our...