The Need for Synchronization

Thread synchronization is required when an application is multithreaded and these threads attempt to use global variables and resources, or the threads need to wait until some event has completed before continuing execution.

First, let's look at why synchronization is required when multiple threads access a global variable. In the following code, a global foating-point variable is declared, and two threads try to perform different actions on that variable.

float g_fValue = 10.0;
void f1()     // called by thread 1
  g_fValue = g_fValue * g_fValue;
void f2()     // called by thread 2
  g_fValue = 3.0 + g_fValue;

It is easy to see that the value in "g_fValue" can be either (10*10) + 3 = 103 or (10+3)*(10+3) = 169 after ...

Get Windows® CE 3.0 Application Programming now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.