OpenSemaphore
// Semaphore.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include "conio.h" #include "windows.h" HANDLE g_hSemaphore = NULL; DWORD WINAPI ThreadSend( LPVOID pParam ) { while( 1 ) { CHAR ch = getch( ); switch( ch ) { case '1': //释放信号 ReleaseSemaphore( g_hSemaphore, 1, NULL ); break; case '5': ReleaseSemaphore( g_hSemaphore, 5, NULL ); break; } } return 0; } DWORD WINAPI ThreadRecv( LPVOID pParam ) { while( 1 ) { //等候信号量的信号 WaitForSingleObject( g_hSemaphore, INFINITE ); printf( "Hello Semaphore\n" ); Sleep( 100 ); } return 0; } void Create( ) { DWORD nThreadID = 0; HANDLE hThread[2] = { NULL }; hThread[0] = CreateThread( NULL, 0, ThreadSend, NULL, 0, &nThreadID ); hThread[1] = CreateThread( NULL, 0, ThreadRecv, NULL, 0, &nThreadID ); WaitForMultipleObjects( 2, hThread, TRUE, INFINITE ); } int main(int argc, char* argv[]) { //创建信号量 g_hSemaphore = CreateSemaphore( NULL, 5, 10, NULL ); Create(); //关闭信号量 CloseHandle( g_hSemaphore ); return 0; }