2 sinat 36503088 sinat_36503088 于 2017.09.10 13:37 提问

使用事件对象进行线程同步,未能正常输出

#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;

}

1个回答

caozhy
caozhy   Ds   Rxr 2017.09.10 14:10
sinat_36503088
sinat_36503088 已解决,谢谢。我错在对数据类型的转换
2 个月之前 回复
sinat_36503088
sinat_36503088 已解决,谢谢。我错在对数据类型的转换
2 个月之前 回复
Csdn user default icon
上传中...
上传图片
插入图片