#include
#include
#define NUMTHREADS 3
#define BUFFER_SIZE 16
#define FOR_TIMES 5
HANDLE hWriteEvents[NUMTHREADS];
HANDLE hReadEvents[NUMTHREADS];
BYTE lpShareBuffer[16]={0};
void MultiEvents(void);
VOID WaitToBuffer(VOID);
DWORD WINAPI ThreadFunction(LPVOID lpParam);
int main(){
MultiEvents();
}
void MultiEvents(void){
HANDLE hThread;
DWORD i;
for(i=0;i<NUMTHREADS;i++){
hWriteEvents[i]=CreateEvent(NULL,FALSE,FALSE,NULL);
if(hWriteEvents[i]==NULL){
printf("createEvent faild(%d)\n",GetLastError());
return;
}
hReadEvents[i]=CreateEvent(NULL,FALSE,FALSE,NULL);
if(hReadEvents[i]==NULL){
printf("createEvent faild(%d)\n",GetLastError());
return;
}
hThread=CreateThread(NULL,0,ThreadFunction,&i,0,NULL);
if(hThread==NULL){
printf("CreateThread failed(%d)\n",GetLastError());
return ;
}
}
WaitToBuffer();
}
VOID WaitToBuffer(VOID){
DWORD dwWaiteResult,j,i;
for(j=0;j<FOR_TIMES;j++){
Sleep(rand()%100);
wsprintfA((LPSTR)lpShareBuffer,"shared%d",j);
for(i=0;j<NUMTHREADS;j++){
if(!SetEvent(hWriteEvents[i])){
printf("setEvent failed(%d)\n",GetLastError());
return;
}
}
dwWaiteResult=WaitForMultipleObjects(NUMTHREADS,hReadEvents,TRUE,INFINITE);//等待所有的线程读完,开始下次写入;
if(dwWaiteResult!=WAIT_OBJECT_0){
printf("Wait error:%d\n",GetLastError());
ExitProcess(0);
}
}
}
DWORD WINAPI ThreadFunction(LPVOID lpParam){
DWORD dwWaitResult;
BYTE lpRead[16];
LPWORD dwThreadIndex;
dwThreadIndex=(LPWORD)lpParam;
DWORD B=*dwThreadIndex ;
printf("%d",B);
for(DWORD j=0;j<FOR_TIMES;j++){
printf("%d",j);
dwWaitResult=WaitForSingleObject(hWriteEvents[B],INFINITE);
switch(dwWaitResult){
case WAIT_OBJECT_0:
Sleep(rand()%10);
CopyMemory(lpRead,lpShareBuffer,16);
printf("%d",j);
break;
default:
printf("Waite error :%d\n",GetLastError());
ExitThread(0);
}
if(!SetEvent(hReadEvents[B])){
printf("SetEvent failed (%d)\n",GetLastError());
return 0;
}
}
return 1;
}