Protecting
Regions of Code with Mutexes
Mutexes are kernel objects, which enables them to be shared between
processes. This also means that mutex-protected sections are heavier weight
than critical sections.
Mutexes are created with a call to CreateMutex() or CreateMutexEx(), which
was introduced in Windows Vista. The call will return the handle to the newly
created mutex object.
The first parameter to the CreateMutex() call is a pointer to the security attributes, or zero if the default
security attributes should be used. The second parameter is a boolean that
indicates if the mutex should be created in the state of being already acquired
by the calling thread. The final parameter is an optional name for the mutex.
The CreateMutexEx call takes the security attributes; an optional name for the mutex; a
flag that has either the value 0 or the value CREATE_MUTEX_INITIAL_OWNER, which indicates that the mutex should be created as owned by the
calling thread; and a mask that sets the access permissions for the mutex (this
can be left as zero).
Once the application has finished with the mutex,
the kernel resources need to be freed by a call to CloseHandle(). Listing 6.18 shows the process of creating and releas-ing a mutex.
Listing 6.18 Creating
and Disposing of Mutexes
HANDLE
mutex;
...
mutex = CreateMutex( 0, 0, 0 );
...
CloseHandle(
mutex );
To acquire the mutex, the application makes a call
to WaitForSingleObject(), which
either returns with the mutex acquired or returns after the specified timeout.
Once the thread has completed, the section of code protected by the mutex can be
released with a call to ReleaseMutex(). The
code in Listing 6.19 shows how to acquire and release the mutex.
Listing 6.19 Acquiring
and Releasing a Mutex
volatile
int counter = 0;
HANDLE mutex;
unsigned int __stdcall test( void * )
{
while ( counter<100 )
{
WaitForSingleObject(
mutex, INFINITE );
int number = counter++;
ReleaseMutex(
mutex );
printf( "ThreadID %i; value =
%i, is prime = %i\n", GetCurrentThreadId(), number, isprime(number) );
}
return 0;
}
int _tmain(int argc, _TCHAR* argv[])
{
HANDLE h1, h2;
mutex =
CreateMutex( 0, 0, 0 );
h1 = (HANDLE)_beginthreadex( 0, 0, &test,
(void*)0, 0, 0); h2 = (HANDLE)_beginthreadex( 0, 0, &test, (void*)1, 0, 0);
WaitForSingleObject( h1, INFINITE );
WaitForSingleObject( h2, INFINITE );
CloseHandle( h1 );
CloseHandle( h2 ); getchar();
CloseHandle(mutex);
return 0;
}
Related Topics
Privacy Policy, Terms and Conditions, DMCA Policy and Compliant
Copyright © 2018-2023 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.