精通windws api 那本书有个小错误,sleep(2000)应该放在后面,不是前面。加入放在前面的话,在执行SetEvent()函数后,主线程就结束了,而子线程还没来得急读出共享内存的数据就被kill了,所以看不到输入结果。放在后面的话,让主线程等带一段时间,让子线程有时间执行。个人理解,错误地方望大牛指出。
1 #include <iostream>
2 #include <windows.h>
3 using namespace std;
4 #define BUFFER_SIZE 16//共享内存
5
6 HANDLE hEevent;
7 BYTE lpShareBuffer[16]={0};
8 void UsingEevent(void);
9 DWORD WINAPI EeventFunction(LPVOID lpPara);
10 void main()
11 {
12 UsingEevent();
13 }
14 void UsingEevent()
15 {
16 HANDLE hThread;
17 hEevent=CreateEvent(NULL,TRUE,FALSE,NULL);
18 if (NULL==hEevent)
19 {
20 cout<<"createevent failed:"<<GetLastError();
21 return;
22 }
23 hThread=CreateThread(NULL,0,EeventFunction,NULL,0,NULL);
24 if (NULL==hThread)
25 {
26 cout<<"create thread failed:"<<GetLastError();
27 }
28
29 CopyMemory(lpShareBuffer,"event",sizeof("event"));
30 SetEvent(hEevent);
31 Sleep(2000);//主线程等待,让子线程有时间执行
32 }
33 DWORD WINAPI EeventFunction(LPVOID lpPara)
34 {
35 DWORD dwWaitResult;
36 dwWaitResult=WaitForSingleObject(hEevent,INFINITE);
37 if (dwWaitResult!=WAIT_OBJECT_0 )
38 {
39 cout<<"wait error:"<<GetLastError()<<endl;
40 return 0;
41 }
42 for (int i=0;i<16;i++)//循环输出内存字符
43 {
44 cout<<lpShareBuffer[i];
45 }
46 if (!ResetEvent(hEevent))//重设置hEvent
47 {
48 cout<<"reset error:"<<GetLastError();
49 return 0;
50 }
51 return 1;
52 }
输出结果:
如果有多个子进程,那么子进程的调度与操作系统和cpu个数有关,如下面程序输出结果:
#include <iostream>
#include <windows.h>
#include <string>
using namespace std;
#define BUFFER_SIZE 16
#define FIVE_EVENTS 5
#define FIVE_THREADS 5
DWORD WINAPI ThreadFunction(LPVOID lpPara);
HANDLE hEvent[5];
HANDLE hMainWrite;
BOOL CreateFiveEvent();
BOOL WirteBuffer();
HANDLE hThread;
BYTE ShareBuffer[16]={0};
string strShar;
int main()
{
CreateFiveEvent();
return 0;
}
BOOL CreateFiveEvent()
{
int i;
for( i=0;i<FIVE_EVENTS;i++)
{
hEvent[i]=CreateEvent(NULL,TRUE,FALSE,NULL);
if (NULL==hEvent[i])
{
cout<<"create event failed"<<GetLastError()<<endl;;
}
hThread=CreateThread(NULL,0,ThreadFunction,(LPVOID)i,NULL,NULL);
if (NULL==hThread)
{
cout<<"create thread failed"<<endl;
}
}
hMainWrite=CreateEvent(NULL,TRUE,FALSE,NULL);
WirteBuffer();
return 0;
}
BOOL WirteBuffer()
{
strShar="hello world";
SetEvent(hMainWrite);
Sleep(200);
return 0;
}
DWORD WINAPI ThreadFunction(LPVOID lpPara)
{
WaitForSingleObject(hMainWrite,INFINITE);
cout<<"第"<<"线程读出数据:"<<strShar<<endl;
ResetEvent(hMainWrite);
return 0;
}
输出在屏幕结果是不确定的:
![]()