1 信号量
通知的作用,和事件类似.但是与事件不同.事件只维护一个值0或者1.信号量维护一个变量,0时无信号,大于0有信号.
2 信号量的使用
2.1 创建信号量
HANDLE CreateSemaphore(LPSECURITY_ATTRIBUTES lpSemaphoreAttributes,
//安全属性
LONG lInitialCount,//初始信号量
LONG lMaximumCount,//最大信号量
LPCTSTR lpName //命名
);
返回创建好的信号量句柄.
2.2 等候信号量
WaitForSingleObjectWaitForMultipleObjects
2.3 释放信号
BOOL ReleaseSemaphore(HANDLE hSemaphore, //信号量句柄
LONG lReleaseCount,//释放信号的数量
LPLONG lpPreviousCount //释放前的数量
);
2.4 关闭信号量
CloseHandle2.5 打开信号量
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;
}