The threads share several variables or a data structure. Often, these multiple variables or the fields of the structure must be consistent among themselves. The operating system could interrupt a thread in the middle of updating these variables. The thread that uses these variables would then be dealing with inconsistent data. The result is a collision, and it’s not difficult to imagine how an error like this could crash the program. What we need are the programming equivalents of traffic lights to help coordinate and synchronize the thread traffic. That’s the critical section. Basically, a critical section is a block of code that should not be interrupted.
Declaring: CRITICAL_SECTION cs ;
Initializing: InitializeCriticalSection (&cs) ;
Entering: EnterCriticalSection (&cs) ;
Leaving: LeaveCriticalSection (&cs) ;
Deleting: DeleteCriticalSection (&cs) ;
The most common use of multiple threads of execution is for programs that find they must carry out some lengthy processing. We can call this a “big job,” which is anything a program has to do that might violate the 1/10-second rule. Obvious big jobs include a spelling check in a word processing program, a file sort or indexing in a database program, a spreadsheet recalculation, printing, and even complex drawing. Of course, as we know by now, the best solution to following the 1/10-second rule is to farm out big jobs to secondary threads of execution. These secondary threads do not create windows, and hence they are not bound by the 1/10-second rule.
Create: hEvent = CreateEvent (&sa, fManual, fInitial, pszName) ;
Set the Event state as signalled: SetEvent (hEvent) ;
Set the Event state as unsignalled: ResetEvent (hEvent) ;
Waiting for the signalled state: WaitForSingleObject (hEvent, dwTimeOut) ;
Waiting for the multiple signalled state: WaitForMultipleObject (…) ;