Home > Articles

  • Print
  • + Share This
Like this article? We recommend

Preventing Threading Problems

Earlier in the article, I said we had a bug in the thread code. This is how to fix it. The bug is the Boolean variable threaddone, which can be corrupted if its value is set outside the thread and the thread is reading it at the same time.

How do we ensure that the data in the thread is not corrupted? One of the best ways is to use WaitForSingleObject to signal the thread (in the example below, by setting the Boolean variable threaddone) so that the data won't be corrupted. To use this function, we can create a semaphore and call WaitForSingleObject, which increments the semaphore. Then call ReleaseSemaphore to decrement the count. Here's the example:

HANDLE hSem;

hSem=CreateSemaphore(NULL,1,2, NULL);



DWORD WINAPI MyThread (POVID pParam)
{
  extern bool threaddone;
    for (;;)
    {
        long previouscount;

        sleep(2); /// so we don't hog the processor or make a race condition

         DWORD dwResult=WaitForSingleObject(hSem, 3);

             if (threaddone) // set in another process so we know to exit
{
          ReleaseSemaphore(hSem,1,&previouscount);   // decrement the count
              return;
              }
         ReleaseSemaphore(hSem,1,&previouscount);     // decrement the count

}
}

So now in another function (or thread) you can set the Boolean value:
....
DWORD dwResult=WaitForSingleObject(hSem, 3);

       threaddone=true; // set the thread to exit

       ReleaseSemaphore(hSem,1,&previouscount);   // decrement the count

......
  • + Share This
  • 🔖 Save To Your Account