#include <iostream> #include <Windows.h> using namespace std; HANDLE hSemaphnore1; HANDLE hSemaphnore2; int global_variable =0; void Threadfun1(LPVOID pParam) { WaitForSingleObject(hSemaphnore1,INFINITE); while(1) { global_variable++; printf("%d\n",global_variable); Sleep(100); //睡眠下,让其他线程有机会抢占 if(global_variable ==10) { ReleaseSemaphore(hSemaphnore2, 1, NULL); //通知线程2 WaitForSingleObject(hSemaphnore1,INFINITE); //让线程1等待 } } } void Threadfun2(LPVOID nParam) { WaitForSingleObject(hSemaphnore2,INFINITE); while(1) { global_variable--; printf("%d\n",global_variable); Sleep(100); if(global_variable ==0) { ReleaseSemaphore(hSemaphnore1, 1, NULL); //通知线程1 WaitForSingleObject(hSemaphnore2,INFINITE); } } } int main() { DWORD threadLidar_receive,threadlidar_process; hSemaphnore1 = CreateSemaphore(NULL,1,1,NULL); hSemaphnore2 = CreateSemaphore(NULL,0,1,NULL); CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) Threadfun1, NULL, 0, &threadLidar_receive); CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) Threadfun2,NULL, 0, &threadlidar_process); Sleep(100); system("pause"); return 0; }