Mutexes and Sharing Them Between Processes
The easiest way to share a mutex between processes is for the mutex to be created with a name. Then other processes can use the OpenMutex() or CreateMutex() function to obtain a handle to the mutex. There are several complexities involved in this:
n Only one of the processes can create the mutex. The others can only open the existing mutex.
n The name of the mutex needs to be unique. If any object of the same name
already exists, then the mutex will fail to be created.
n The name of the mutex needs to be passed to the other processes.
All of these issues are surmountable, but they add some complexity.
The code in Listing 6.29 creates two copies of the same processes and enables them to share a mutex.
Listing 6.29 Sharing Mutexes Between Processes
int _tmain( int argc, _TCHAR* argv )
ZeroMemory( &process_info, sizeof(process_info) ); ZeroMemory( &startup_info, sizeof(startup_info) ); startup_info.cb = sizeof(startup_info);
sharedmutex=CreateMutex( 0, 0, L"mymutex12234" );
if ( GetLastError() != ERROR_ALREADY_EXISTS )
if ( CreateProcess( argv, 0, 0, 0, 0, 0, 0, 0, &startup_info, &process_info )==0 )
printf( "ERROR %i\n", GetLastError() );
WaitForInputIdle( process_info.hProcess, INFINITE );
WaitForSingleObject( sharedmutex, INFINITE );
for (int i=0; i<1000; i++)
printf( "Process %i Count %i\n", GetCurrentProcessId(), i );
ReleaseMutex( sharedmutex );
CloseHandle( sharedmutex );
The mutex is created through a call to CreateMutex(). If the mutex already exists, then a handle to the existing mutex is returned, and the error condition is set to ERROR_ALREADY_EXISTS. If this is not the error condition, then it is assumed by the code that this means that the mutex was created by the calling process and therefore that the calling process needs to start a second copy of itself.
The call to CreateMutex() takes the name of the mutex. In this case, the name is mymutex12234. The string is specified with an uppercase L, which tells the compiler to make it a wide-character string. The same effect could have been achieved by wrapping the string in TEXT(...).
In this example, the shared mutex is used to ensure that only one of the two processes counts up to 1,000 at a time. If there was no mutex, then both processes could be active simultaneously, and the console output would be a mix of the output from both processes. Using the mutex, the output is from just one of the processes at a time.