c++windows编程:关于线程已经ResetEvent(tHandle);了,为什么WaitForSingleObject下面的代码还能执行呢
- C/C++ code
#include <windows.h>#include <process.h>#include <iostream>using namespace std;long g_iData = 0; // 全局变量// 线程体unsigned int __stdcall ThreadFunc(void* param){ g_iData++; //InterlockedExchangeAdd(&g_iData,155); return 0;}unsigned int __stdcall ThreadFunc2(void* param){ g_iData=g_iData+3; //InterlockedExchange(&g_iData, 4); return 0;}void main(){ unsigned int tid1 = 0; unsigned int tid2 = 0; HANDLE tHandle = NULL; HANDLE tHandle2 = NULL; tHandle= (HANDLE)_beginthreadex(NULL, 0, ThreadFunc, 0, 0, &tid1); ResetEvent(tHandle); WaitForSingleObject(tHandle, INFINITE);//不等待线程1结束的话,可能会有下面的输出语句先执行而输出1 cout<<g_iData<<endl; cout<<g_iData<<endl; tHandle2 = (HANDLE)_beginthreadex(NULL, 0, ThreadFunc2, 0, 0, &tid2); cout<<g_iData<<endl; system("pause"); }如图里:
明明已经ResetEvent(tHandle);了,为什么WaitForSingleObject(tHandle, INFINITE);下面的代码还能执行呢。
跪求高人指点!!!
[解决办法]
检查WaitForSingleObject的返回值,你没CreateEvent,所以WaitForSingleObject可能失败了
[解决办法]
tHandle不是event的句柄,要createevent
[解决办法]
你使用函数都不看这个函数是什么功能,需要什么参数的吗。
ResetEvent:This function sets the state of the specified event object to nonsignaled.
你传个线程句柄是无效的,虽然都是句柄,但分属不同内核对象,内部实现也不同,不能这么混用,所以GetLastError返回6,意思是 the handle is invalid,再者,创建的event是无信号的,reset下眉什么意义
[解决办法]