Avoiding deadlocks
When two or more tasks want to use the same resource, we have a race condition. Until one task finishes using the resource, the other task cannot get access to it. This is known as a deadlock, and we must avoid deadlocks at all costs. For example, resource Collision
and resource Audio
are used by process Locomotion
and process Bullet
:
Locomotion
starts to useCollision
Locomotion
andBullet
try to start usingAudio
Bullet
"wins" and getsAudio
firstNow
Bullet
needs to useCollision
Collision
is locked byLocomotion
, which is waiting forBullet
Getting ready
For this recipe, you will need a Windows machine and an installed copy of Visual Studio.
How to do it…
In this recipe, we will find out how easy it is to avoid deadlocks:
#include <thread> #include <string> #include <iostream> using namespace std; void Physics() { for (int i = 0; i > -100; i--) cout << "From Thread 1: " << i << endl; } int main() { std::thread t1(Physics...