您的位置:首页 > 其它

多个线程互同步问题

2011-09-22 15:41 337 查看
#include <windows.h>
#include <stdio.h>

#define NUMTHREADS 3
#define BUFFER_SIZE 16
#define FOR_TIMES 5

HANDLE hWriteEvents[NUMTHREADS];
HANDLE hReadEvents[NUMTHREADS];
BYTE lpSharedBuffer[16]={0};

void MultiEvents(void);
VOID WriteToBuffer(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 failed.(%d)\n",GetLastError());
return;
}
hReadEvents[i] = CreateEvent(NULL,FALSE,FALSE,NULL);
if(hReadEvents[i]==NULL){
printf("CreateEvent failed.(%d)\n",GetLastError());
return;
}
hThread = CreateThread(NULL,0,ThreadFunction,i,0,NULL);
if(hThread == NULL){
printf("CreateThread failed.(%d)\n",GetLastError());
return;
}
}
WriteToBuffer();
}

VOID WriteToBuffer(VOID){
DWORD dwWaitResult,i,j;
for(j=0;j<FOR_TIMES;j++){
Sleep(rand()%100);
wsprintf(lpSharedBuffer,"shared %d",j);
for(i=0;i<NUMTHREADS;i++){
if(!SetEvent(hWriteEvents[i])){
printf("SetEvent failed.(%d)\n",GetLastError());
return;
}
}
dwWaitResult = WaitForMultipleObjects(NUMTHREADS,hReadEvents,TRUE,INFINITE);
if(dwWaitResult != WAIT_OBJECT_0){
printf("Wait error.(%d)\n",GetLastError());
ExitProcess(0);
}
}
}

DWORD WINAPI ThreadFunction(LPVOID lpParam){
DWORD dwWaitResult;
BYTE lpRead[16];
DWORD j = 0;
DWORD dwThreadIndex = (DWORD)lpParam;
for(j=0;j<FOR_TIMES;j++){
dwWaitResult = WaitForSingleObject(hWriteEvents[dwThreadIndex],INFINITE);
switch (dwWaitResult){
case WAIT_OBJECT_0:
Sleep(rand()%10);
CopyMemory(lpRead,lpSharedBuffer,16);
break;
default:
printf("Wait error:%d\n",GetLastError());
return 0;
}
printf("线程%u\t第%d次读,内容:%s\n",dwThreadIndex,j,(LPSTR)lpRead);
}
return 1;
}


本文出自 “About:Blank H4cking” 博客,请务必保留此出处http://pnig0s1992.blog.51cto.com/393390/671381
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐