This is a small multi-threaded application that simulates cars moving in random directions. Each car is moving independently from the other and is associated with a separate thread. A class
CCarThread, derived from
CWinthread, is written for this purpose. (The
m_bAutoDelete parameter of
CWinThread is set to
false, so that the object survives even after the thread is terminated.)
A car is drawn using a bitmap resource and the parent window's device context. Since only one thread can own the device context at a time, a
critical_section cs is used to synchronize the ownership.
The car can move in one of the following eight directions. The eight directions are assumed.
A separate bitmap for each direction is stored in the resources.
The random motion of the cars is obtained by the
RandomVelocityChange() function which changes the velocity at a random time. In order to give this simulation a realistic look, the allowable change in the velocity is as follows:
where the solid black line shows the current direction of motion and the dotted black line shows the allowable directions it can change to, and the solid blue lines show the directions which are not allowed for the current direction to change to.
To detect the possibility of the collision of a car, each car thread checks itself against all the other cars. The thread pointer of all the cars are stored in a vector which is a static member of
CCarThread. And any thread can access that vector using the
critical_secion csCrash, which is also a static member of
The collision check is as follows: if the rectangular area occupied by this car overlaps that of another car then the two cars collide. (This is a type of distributed control.) It then signals the other car to terminate. Note that in order to avoid a deadlock, the cars which collide are moved to a separate array and are then killed.
In order to kill a thread, the event
m_hEventKill of that thread is set, and then we wait for the thread to terminate itself. It then sends a message to the main window to remove or kill itself. You can remove all the cars any time during a simulation.
I am a visual C++ programmer, currently working in Industrial Control Systems in Sheffield, United Kingdom as a Senior Programmer and Researcher. You can contact me by sending email to email@example.com