// 06 信号量解决线程同步问题.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include <windows.h> int g_n; HANDLE hSemaphore; DWORD WINAPI ThreadPro1(LPVOID lpThreadParameter){ for (int i = 0; i < 10000000; i++) { WaitForSingleObject(hSemaphore, -1); g_n++; printf("我在线程1:%d ", g_n); Sleep(100); ReleaseSemaphore(hSemaphore,1,NULL); } return 0; } DWORD WINAPI ThreadPro2(LPVOID lpThreadParameter){ for (int i = 0; i < 10000000; i++) { WaitForSingleObject(hSemaphore, -1); g_n++; printf("我在线程2:%d ", g_n); Sleep(100); ReleaseSemaphore(hSemaphore,1, NULL); } return 0; } int _tmain(int argc, _TCHAR* argv[]){ HANDLE hThread1 = 0, hThread2; //创建一个创建一个锁孔的信号量 hSemaphore = CreateSemaphore(NULL,1,1,NULL); hThread1 = CreateThread(NULL, NULL, ThreadPro1, NULL, NULL, NULL); hThread2 = CreateThread(NULL, NULL, ThreadPro2, NULL, NULL, NULL); WaitForSingleObject(hThread1, -1); WaitForSingleObject(hThread2, -1); printf("%d", g_n); return 0; }