//ThreadAction.h
#pragma once
#ifndef _THREADACTION_H_
#define _THREADACTION_H_
#include "stdafx.h"
#include <Windows.h>
#include <stdio.h>
#include <process.h>
#define MAXTHREADSIZE 3
#define BUFFER_SIZE 16
#define FOR_TIMES 5 //读写次数
void MultiEvents(void);
VOID WriteToBuffer(VOID);
unsigned __stdcall ThreadFunction(LPVOID lpParam);
#endif
//ThreadAction.cpp
#include "StdAfx.h"
#include "ThreadAction.h"
HANDLE hWriteEvent[MAXTHREADSIZE];
HANDLE hReadEvent[MAXTHREADSIZE];
LPTSTR szSharedBuffer = new TCHAR[16];
void MultiEvents(void)
{
//创建线程,读共享内存
//主线程写共享内存
//每个线程都有对应的读写同步事件
HANDLE hThread;
DWORD i = 0;
DWORD dwThreadID;
for(i=0;i<FOR_TIMES;++i)
{
//创建写事件
hWriteEvent[i] = CreateEvent(NULL,FALSE,FALSE,NULL);
if (hWriteEvent[i]==NULL)
{
printf("Failed to Create Write Event %d",i);
return;
}
//创建读事件
hReadEvent[i] = CreateEventA(NULL,FALSE,FALSE,NULL);
if (hReadEvent[i] == NULL)
{
printf("Failed to Create Read Event %d",i);
return;
}
//创建线程
hThread = (HANDLE)_beginthreadex(NULL,0,ThreadFunction,(void*)i,0,(unsigned int*)&dwThreadID);
if (hThread == NULL)
{
printf("Failed to Create Thread:%d\n",GetLastError());
return;
}
}
WriteToBuffer();
}
VOID WriteToBuffer(VOID)
{
DWORD dwWaitResult;
DWORD i = 0,j = 0;
for (i=0;i<FOR_TIMES;++i)
{
Sleep(100);
//写入共享内存
wsprintfA((LPSTR)szSharedBuffer,"shared%d",i);
//将线程对应的写事件置为触发,表示写事件完成,读操作可以进行
for(j=0;j<MAXTHREADSIZE;++j)
{
//printf("Succeess\n");
if (!SetEvent(hWriteEvent[j]))
{
printf("Failed to SetEvent %d\n",GetLastError());//第一次调试的时候要发现第一个之后出现了无效句柄,检查之后发现是因为第一次用了i做ID,结果i被修改了,for出错
return;
}
}
//等待所有的线程读完,开始下一次写入
dwWaitResult = WaitForMultipleObjects(MAXTHREADSIZE,hReadEvent,TRUE,INFINITE);
if(dwWaitResult!=WAIT_OBJECT_0)
{
printf("Wait Error %d\n",GetLastError());
ExitProcess(0);
}
}
}
unsigned __stdcall ThreadFunction(LPVOID lpParam)
{
DWORD dwWaitResult;
BYTE lpRead[16];
DWORD i = 0;
DWORD dwThreadIndex = (DWORD)lpParam;
for(i=0;i<FOR_TIMES;++i)
{
dwWaitResult = WaitForSingleObject(hWriteEvent[dwThreadIndex],INFINITE);
switch(dwWaitResult)
{
case WAIT_OBJECT_0:
Sleep(10); //处理数据
CopyMemory(lpRead,szSharedBuffer,16);
break;
default:
printf("Wait Error %d\n",GetLastError());
_endthreadex(dwThreadIndex);
}
//将读事件置为触发
if (!SetEvent(hReadEvent[dwThreadIndex]))
{
printf("Failed to SetEvent : %d\n",GetLastError());
return 0;
}
printf("线程%u 第%d次被读,内容:%s\n",dwThreadIndex,i+1,(LPSTR)lpRead);
}
return 1;
}
//main.cpp
#include "stdafx.h"
#include "ThreadAction.h"
int _tmain(int argc, _TCHAR* argv[])
{
MultiEvents();
return 0;
}
网友评论