Semaphores are used in multiple threads, primarily for thread synchronization or to limit the number of threads running.
So-called synchronization, when process 1 runs thread 1, process 2 runs thread 2, process 2 must be completed at the end of process 1 before execution can begin. What you will do, all you need is a signal for the end of process 1.
Before the signal comes, let the thread 2 wait in a place first, this way and the mutex is a bit similar, mutual exclusion in a sense is also a kind of synchronization, but the mutex is more inclined to protect the common resources. When the signal volume is greater than 0, it represents a signal and does not need to wait, but not just 1.
The following example sets up 3 threads, setting the maximum of 2 processes at the same time.
#include <Windows.h>#include<iostream>using namespacestd;//Create a SemaphoreHANDLE Hsemaphore;//with ParametersDWORD WINAPI MyThread2 (lpvoid lpparamter) { while(1) {WaitForSingleObject (hsemaphore,infinite); cout<<"MyThread1 runing:"<<"Thread 2"<<Endl; Sleep ( -); ReleaseSemaphore (Hsemaphore,1, NULL);//release Semaphore }}//No ParametersDWORD WINAPI MyThread1 (lpvoid lpparamter) { while(1) { //signal Volume minus 1, if equal to 0 to go to sleep, to be more than 0 after reducingWaitForSingleObject (Hsemaphore,infinite); cout<<"MyThread2 runing"<<"Thread 1"<<Endl; Sleep ( -); //signal Volume plus 1ReleaseSemaphore (Hsemaphore,1, NULL);//release Semaphore }}//No ParametersDWORD WINAPI MyThread3 (lpvoid lpparamter) { while(1) { //signal Volume minus 1, if equal to 0 to go to sleep, to be more than 0 after reducingWaitForSingleObject (Hsemaphore,infinite); cout<<"MyThread2 runing"<<"Thread 3"<<Endl; Sleep ( -); //release semaphore, signal volume plus 1ReleaseSemaphore (Hsemaphore,2, NULL); }}intMain () {//creates a semaphore, 2 is the initial value, and 3 is the maximumHsemaphore =createsemaphore (NULL,2,3, NULL); //The third parameter is the address of the thread function, and the fourth parameter is the parameter pointer to the threadHANDLE hthread = CreateThread (NULL,0, MyThread1, NULL,0, NULL); //release handleCloseHandle (hthread); HANDLE HThread1= CreateThread (NULL,0, MyThread2, NULL,0, NULL); CloseHandle (Hthread); HANDLE hThread3= CreateThread (NULL,0, MyThread3, NULL,0, NULL); //release handleCloseHandle (HTHREAD3); while(1); return 0;}
As a result you can see that three threads alternately run 2
Multi-thread semaphore (by C + +)