// Semaphore.cpp : Defines the entry point for the console application.
//
//原子锁---针对于单条指令
//临界区---针对于一块代码
//事件-----通知执行 有发送 有接收
//互斥-----有多个线程 只有一个执行
//信号量---维护了一组数据
//可等候定时器-更精确的时间去执行相关代码
#include "stdafx.h"
#include "windows.h"
#include "conio.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;
case '10':
ReleaseSemaphore(g_hSemaphore,10,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 tID=0;
HANDLE hThread[2]={NULL};
hThread[0]=CreateThread(NULL,0,ThreadSend,NULL,0,&tID);
hThread[1]=CreateThread(NULL,0,ThreadRecv,NULL,0,&tID);
WaitForMultipleObjects(2,hThread,true,INFINITE);
}
int main(int argc, char* argv[])
{
//创建信号量 表示还有5个剩余位置
g_hSemaphore=CreateSemaphore(NULL,5,10,NULL);
Create();
getch();
CloseHandle(g_hSemaphore);
return 0;
}
线程信号量 释放 信号量队列等14.4.29
最新推荐文章于 2024-05-26 16:44:28 发布