Game Development Reference
In-Depth Information
zero, it sets the bit to one, all in one operation that cannot be interrupted by the CPU
switching from one thread to another.
Traditionally, a semaphore is set to an integer value that denotes the number of
resources that are free. When a process wishes to gain access to a resource, it decre-
ments the semaphore in an atomic operation, using a test-and-set. When it is done
with the resource, it increments the semaphore in the same atomic operation. If a
process finds the semaphore equal to zero, it must wait.
A mutex is a binary semaphore, and it is generally used to give a process exclusive
access to a resource. All others must wait.
Windows has many different ways to handle process synchronization. A mutex can
be created with CreateMutex() , and a semaphore can be created with Create
Semaphore() . But since these synchronization objects can be shared between Win-
dows applications, they are fairly heavyweight and shouldn ' t be used for high perfor-
mance thread safety in a single application, like our game. Windows programmers
should use the critical section.
The Windows Critical Section
The critical section under Windows is a less expensive way to manage synchroniza-
tion among the threads of a single process. Here
'
s how to put it to use:
DWORD g_ProtectedTotal = 0;
DWORD g_maxLoops = 20;
CRITICAL_SECTION g_criticalSection;
DWORD WINAPI ThreadProc( LPVOID lpParam )
{
DWORD maxLoops = *static_cast<DWORD *>(lpParam);
DWORD dwCount = 0;
while( dwCount < maxLoops )
{
++dwCount;
EnterCriticalSection(&g_criticalSection);
++g_ProtectedTotal;
LeaveCriticalSection(&g_criticalSection);
}
return TRUE;
}
void CreateThreads()
{
 
 
Search WWH ::




Custom Search