If lpName matches the name of an existing named mutex object, this function requests MUTEX_ALL_ACCESS access to the existing object. In this case, thebInitialOwner parameter is ignored because it has already been set by the creating process. If the lpMutexAttributes parameter is not NULL, it determines whether the handle can be inherited, but its security-descriptor member is ignored.
If lpName is NULL, the mutex object is created without a name.
If lpName matches the name of an existing event, semaphore, waitable timer, job, or file-mapping object, the function fails and the GetLastError function returns ERROR_INVALID_HANDLE. This occurs because these objects share the same name space.
Terminal Services: The name can have a "Global\" or "Local\" prefix to explicitly create the object in the global or session name space. The remainder of the name can contain any character except the backslash character (\). For more information, see Kernel Object Name Spaces.
#include <windows.h> #include <stdio.h> static int number=10; HANDLE Mutex; DWORD WINAPI ThreadOne(LPVOID lpParameter) { while(1) { WaitForSingleObject(Mutex,INFINITE); if(number>0) { printf("窗口1售出第%d张票...\n",number); number--; Sleep(1000); } ReleaseMutex(Mutex); } return 0; } DWORD WINAPI ThreadTwo(LPVOID lpParameter) { while(1) { WaitForSingleObject(Mutex,INFINITE); if(number>0) { printf("窗口2售出第%d张票...\n",number); Sleep(1000); number--; } ReleaseMutex(Mutex); } return 0; } int main() { HANDLE HOne,HTwo; Mutex=CreateMutex(NULL,FALSE,NULL); printf("***********************vpoet******************\n"); HOne=CreateThread(NULL,0,ThreadOne,NULL,0,NULL); printf("窗口1售票开始:\n"); HTwo=CreateThread(NULL,0,ThreadTwo,NULL,0,NULL); printf("窗口2售票开始:\n"); CloseHandle(HOne); CloseHandle(HTwo); while(TRUE) { if(number==0) { printf("不好意思,票卖完了!\n"); CloseHandle(Mutex); return 0; } else { continue; } } return 0; }