Dr. Dobb's is part of the Informa Tech Division of Informa PLC

This site is operated by a business or businesses owned by Informa PLC and all copyright resides with them. Informa PLC's registered office is 5 Howick Place, London SW1P 1WG. Registered in England and Wales. Number 8860726.


Channels ▼
RSS

How to Start a Multi-threading Relationship


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.


Related Reading


More Insights






Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

 
Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.