We said before the critical section, like a small room, Zhang San in, John Doe can not enter, if Li four to enter, must wait for Zhang three out.
Today we are going to talk about mutexes, like an object, which can only be held by one thread at a time. In this way, the synchronization of threads can be achieved through mutual exclusion locks.
First, create
The method of creating a mutex is to call the function CreateMutex:
CreateMutex (&sa, Binitialowner, szName);
The first parameter is a pointer to the security_attributes struct, which, in general, can be nullptr.
The second argument type is bool, which indicates whether the mutex is held by the current thread after it is created.
The third parameter type is a string (const tchar*), which is the name of the mutex and, if it is nullptr, the mutex is anonymous.
Cases:
HANDLE Hmutex = CreateMutex (nullptr, FALSE, nullptr);
The above code creates an anonymous mutex, which is created after the current thread does not hold the mutex.
Second, hold
The WaitForSingleObject function allows a thread to hold a mutex. Usage:
WaitForSingleObject (Hmutex, dwtimeout);
This function is more useful. This only describes the role of the first argument as a mutex handle.
Its role is to wait until a certain time, or, other threads do not hold Hmutex. The second parameter is the time (in milliseconds) to wait, and if the parameter is INFINITE, the function waits.
Iii. Release
The ReleaseMutex function allows the current thread to "release" a mutex (without holding it), so that other threads can hold it. Usage
ReleaseMutex (Hmutex);
Iv. Destruction
When a mutex is no longer needed by the program, it is destroyed.
CloseHandle (Hmutex);
V. Naming mutexes
If the third argument of the CreateMutex function passes in a string, the created lock is named . When a named lock is created, neither the current process nor any other process can create a lock of the same name until the lock is destroyed. This feature allows a program to run at most one instance at the same time.
As follows:
int __stdcall wWinMain (hinstance, HINSTANCE, wchar_t, int) {HANDLE Hmutex = CreateMutex (nullptr, FALSE, L "Virtuanes"); if (Hmutex = = nullptr)//There is already another instance running {return 0; }//Other code}
Windows thread Synchronization "3" Mutex (mutex)