Thread Synchronization Methods include critical section, mutex, event, and semaphore.
The front side talked about mutex thread synchronization-Windows core programming-mutexes. In this chapter, I will introduce the semaphores (semaphore) thread synchronization.
Theoretically, mutex is a degradation of semaphore. If you generate a semaphore and set the maximum value to 1, it is a mutex. Therefore, mutex is also known as binary semaphore. If a thread has a binary semaphore, no other thread can gain its ownership. However, in Win32, the ownership of these two things has completely different meanings, so they cannot be exchanged and used. semaphore is not like mutex, and it does not have the so-called "Wait
The abandoned status can be detected by other threads.
Every time a lock action succeeds, the current value of semaphore is reduced by 1. You can use any wait... () function to lock a semaphore. If the current value of semaphore is not 0, wait... () The function will return immediately, which is similar to mutex. When no thread has mutex, wait... () The function returns immediately.
Note: If the lock is successful, you will not receive the semaphore ownership. Because more than one thread can lock a semaphore at the same time. So it doesn't have much practical significance to talk about the ownership of semaphore. There is no such thing as "exclusive lock" on semaphore. Because there is no ownership concept, a thread can call the wait... () function repeatedly to generate new locks. This is absolutely different from mutex: A thread with mutex will not be blocked no matter how many times the wait... () function is called.
Unlike mutex, the thread that calls releasesemaphore () does not necessarily have to be the one that calls wait.
Any thread can call releasesemaphore () at any time to unlock the semaphore locked by any thread.
The following is a summary of the commonly used functions in the three synchronous modes.
Critical Section |
Mutex |
Semaphores |
Critical_section Initializecriticalsection () |
Createmutex () Openmutex () |
Createsemaphore |
Entercriticalsection () |
Waitforsingleobject () Waitformultipleobjects () Msgwaitformultipleobjects () |
Waitforsingleobject () Waitformultipleobjects () Msgwaitformultipleobjects () ... |
Leavecriticalsection () |
Releasemutex () |
Releasesemaphore () |
Deletecriticalsection () |
Closehandle () |
Closehandle () |
Event thread synchronization ----- window core programming-kernel object Thread Synchronization