1. mutex "critical zone" between different processes, cross-process
#include " the stdafx.h " #include <WINDOWS.H> int main ( int argc, char * the argv []) { // create a mutex HANDLE g_hMutex the CreateMutex = (NULL, FALSE, (LPCWSTR) " the XYZ " ) ; // Create out whether a second parameter signal // wait signal (token) the WaitForSingleObject (g_hMutex, of INFINITE); for ( int I = 0 ; I < 10 ; I ++ ) { Sleep ( 1000 ); the printf ( " the Y thread B process:% D \ n- " , I); } // release the token (signal) the ReleaseMutex (g_hMutex); return 0 ; }
Examples of anti-mutex to open:
// mutex .cpp: Defines the entry point console application. // #include " the stdafx.h " #include <WINDOWS.H> int main () { // create a mutex HANDLE g_hMutex the CreateMutex = (NULL, FALSE, (LPCWSTR) " to prevent multiple open " ); // first Create two parameters are signaled out // wait signal (token) DWORD dwRet = the GetLastError (); iF (g_hMutex) { iF (ERROR_ALREADY_EXISTS == dwRet) { the CloseHandle (g_hMutex); return 0 ; } } the else { the printf ( " creation fails, the program exits \ n-! " ); the CloseHandle (g_hMutex); return 0 ; } for ( int I = 0 ; I < 10 ; I ++ ) { Sleep ( 1000 ); the printf ( " A Process thread X: D% \ n- " , I); } return 0 ; }