The mutex kernel object contains a count, thread ID, and a recursive count. The mutex is the same as that of the key segment, but the mutex is the kernel object, which means it is much slower than the key segment. However, threads in different processes can access the same mutex.
The thread ID identifies a thread with a mutex. The recursive count indicates the number of times a thread has a mutex.
Mutex rules:
- If the thread ID is 0, the mutex is not owned by any thread.
- If the thread ID is not 0, a thread already has a mutex. At this time, the mutex is not triggered.
- After a thread obtains the mutex, it does not release the mutex before exiting the thread. In this way, other threads call the function to obtain the mutex, and the returned value is wait_abandoned.
Create a mutex using the createmutex function. Release a mutex using releasemutex.
HANDLE WINAPI CreateMutex( __in_opt LPSECURITY_ATTRIBUTES lpMutexAttributes, __in BOOL bInitialOwner, __in_opt LPCTSTR lpName);
BOOL WINAPI ReleaseMutex( __in HANDLE hMutex);
The second parameter for creating mutex is true, which indicates that the mutex is owned by the thread where it is created. The opposite is false. Other parameters are described several times in other kernel objects.
I usually use mutex to make the program run only one instance.
Write an example to test the rule 3.
# Include <windows. h ># include <iostream> using namespace STD; handle hmutex; DWORD winapi threadproc (lpvoid LP) {waitforsingleobject (hmutex, infinite); Return 0;} DWORD winapi waitproc (lpvoid LP) {sleep (1000); DWORD dwresult = waitforsingleobject (hmutex, infinite); If (dwresult = wait_abandoned) {cout <"" <Endl ;} releasemutex (hmutex); Return 0;} int main (INT argc, char * argv []) {hmutex = createmutex (null, false, null); handle hthread [2]; hthread [0] = createthread (null, 0, threadproc, 0, 0, null); hthread [1] = createthread (null, 0, waitproc, 0, 0, null); waitformultipleobjects (2, hthread, true, infinite); closehandle (hthread [0]); closehandle (hthread [1]); closehandle (hmutex); Return 0 ;}