Communication Is Key
The best way to build trust is communication. When communication breaks down, that's when hearts are broken and feelings are hurt, and you are left sitting alone in your house, crying, and listening to "Lay Lady Lay" on a constant loop*sigh*. Anyway, the same thing is true with threading. When communication breaks down between threads, all of a sudden your game is crashing at odd times with odd messages, and you have no idea what happened.
Knowing when a thread is finished with its data is a crucial part of multi-threaded programming. Event handles and critical sections are two great ways to communicate to other threads and synchronize data sharing between threads. Knowing when and where to use these synchronization techniques is like being a master of flirting with the ladies. If I were to say to you I was a ladies man, you would not agree.
I do, however, know where to use which synchronization technique. That's hot in its own way, right? Right!? If you only need to see if a thread has finished processing, event handles are the best way to go about it. The FFT example given previously is perfect for this synchronization setup. Here is some pseudo-code that offers a solid way to ensure that data is being used only when the FFT thread has finished it.
HANDLEhFFTFinished; HANDLEhFFTStart; void FFT() { for(;;) { //Wait until the main thread signals this thread for analysis WaitForSingleObject(hFFTstart, INFINITE); ResetEvent(hFFTStart); //Reset the start event //Run FFT and analyze data SetEvent(hFFTFinished); // Signal that the analysis is finished } } void Render() { // WaitForSingleObject with the second parameter 0 will check // the handle and return the status without waiting if(TRUE == WaitForSingleObject(hFFTFinished, 0)) { //Copy and render with new data ResetEvent(hFFTFinished); //Reset the finished event SetEvent(hFFTStart); // Set the start event so the FFT // can analyze again } else { //Render with old data } }
Our function FFT is run on a separate thread. You'll notice that all of the analysis is in an infinite for loop with a wait event at the beginning. The two HANDLEANDLE objects, hFFTFinished, and hFFTStart, are the two-way lines of communication between the FFT thread and the main thread. Basically, hFFTStart is an event handle that is set to a signaled state by the main thread. When the main thread signals hFFTStart with SetEvent(), the FFT thread begins the analysis. The main thread runs Render() and checks each frame with the WaitForSingleObject function if the FFT thread has finished its data analysis. By calling WaitForSingleObject with 0 as the second parameter (the second parameter is the amount in milliseconds that the wait should . . .wait), the function checks the status of the event, returning TRUE if it has been signaled and FALSE if it has not. If it has been signaled as complete, the main thread renders with the new data, resets hFFTFinished with ResetEvent, and then the hFFTStart handle is signaled to run another FFT analysis. This setup is a very efficient and extremely secure way to do two-way communication between two threads.
When you need exclusive access to data, such as when a thread will adjust memory that is to be used by another thread, then critical sections are the way to go. As pointed out above, without synchronization the UpdateBullet function could cause a memory fault if it isn't synchronized. So how do we fix this? Let's watch!
CRITICAL_SECTIONbulletSection; Bullet**pBullets; void UpdateBullets() { //Loop forever, update constantly for(;;) { for(int i=0; i<numBullets;i++) { EnterCriticalSection(&bulletSection); for(int i = 0; i<numBullets I++) { if(TRUE==IsHittingSomething(pBullet)) { //Destroy the bullet, free memory } Else { //Update bullet information } } LeaveCriticalSection(&bulletSection); } } void Render() { EnterCriticalSection(&bulletSection); //Render the bullets LeaveCriticalSection(&bulletSection): }
Now, this setup ensures that when data is used for rendering it isn't being freed. Upon entering the critical section, whichever thread enters first obtains exclusive access to the data and upon releasing that access, the other thread is allowed to do whatever it needs to do with the data.
Event handles and critical sections are the most common methods for synchronization in threading environments. As you can see in the above examples, a little bit of planning and forethought will allow you to communicate efficiently between threads and maintain the trust between the threads in your application.
Planning for the Future
It's always good to look toward the future and identify your goals. This article represents the initial steps in building a nice threading model. Tune in next time when I will go into more detail on ways to distribute the work and synchronize to more than one thread to take advantage of today's multi-core processors.