创建信号灯, 一种内核对象的同步方式
使用步骤如下
1,创建信号灯
HANDLE hCounter = CreateSemaphore(NULL,2,2,"iCounter")
2,打开信号灯
hCounterIn=OpenSemaphore(SEMAPHORE_ALL_ACCESS,FALSE,"iCounter")
3, 等待信号灯WaitForSingleObject(hCounterIn,INFINITE); 或
dwWait = WaitForMultipleObjects(2, hWait, FALSE, INFINITE);
4, 释放信号灯ReleaseSemaphore(hCounterIn,1,NULL);
5, 关闭句柄了CloseHandle(hCounter)
信号量,Event 等等这些东西 用来实现多进程/多线程通讯
进程1
{
HANDLE hEvent = CreateEvent( NULL, TRUE, FALSE, "MyName" );
getch();
SetEvent( hEvent );//传递信号
CloseHandle( hEvent );
return 0;
}
进程2
HANDLE hEvent = OpenEvent( SYNCHRONIZE, FALSE, "MyName" );
if( hEvent != NULL )
{
WaitForSingleObject( hEvent, INFINITE );
MessageBox(NULL, "接收到信号",0 ,MB_ICONINFORMATION);
CloseHandle( hEvent );
}
return 0;
DWORD WINAPI ThreadProc1( LPVOID lpParamenter);int main(int argc, char* argv[]){
// 更改第二个参数你会发现PulseEvent的用处,第三个参数用来设置初始状态是Singled还是Unsingled。
hEvent = CreateEvent(NULL, TRUE, TRUE, "abc");
hThread = CreateThread(NULL, NULL, ThreadProc1, NULL, NULL, NULL);
Sleep(1);
printf("1\n");
PulseEvent(hEvent);
Sleep(1);
printf("2\n");
SetEvent(hEvent);
Sleep(1);
printf("3\n");
ResetEvent(hEvent);
printf("4\n");
PulseEvent(hEvent);
Sleep(1);
printf("5\n");
TerminateThread(hThread, NULL);
printf("Hello World!\n");
return 0;
}
DWORD WINAPI ThreadProc1( LPVOID lParamenter )
{
int iCount = 0;
while( true )
{
printf("xx%d\t", iCount++);
WaitForSingleObject(hEvent, INFINITE);
printf("**%d\t", iCount++);
}
return NULL;
}
阅读(2398) | 评论(3) | 转发(0) |