Calling SetEvent with an invalid handle

I have an application where a thread calls SetEvent and another thread waits for that event. However, CreateEvent was never called.

The SetEven returns false (ERROR_INVALID_HANDLE), and the WaitForSingleObject returns WAIT_FAILED

Yesterday, we commit something apparently not related : two lines of code in the .rc removing buttons from a toolbar.

Suddently, on realease-XP-32 the WaitForSingleObject returns WAIT_TIMEOUT .

But I wonder :

1- Why a commit (apparently unrelated) in the ressources did make a change in the return of the WaitForSingleObject ?

2- When I launch the application (XP32) from Visual Studio I get a different behavior than when I launch the application directly. WaitForSingleObject() returns WAIT_FAILED instead of time out. Any idea why ?


Since you never called CreateEvent , your SetEvent and WaitForSingleObject were using an uninitialized variable. The contents of uninitialized variables are indeterminate, so you end up passing an unknown value to SetEvent and WaitForSingleObject . It appears that with the old code, the memory usage pattern happened to result in a situation where the uninitialized variable had a value that was not a valid handle, so you got ERROR_INVALID_HANDLE . After making your change, the memory usage pattern changed, and now the uninitialized variable has a value that happens to be a valid handle, so the WaitForSingleObject function dutifully waits for it. That handle happens to refer to an object that is not signaled, so the WaitForSingleObject call times out and returns WAIT_FAILED .

In other words, the seemingly unrelated change exposed a pre-existing bug. Using uninitialized data can lead to nonlocal effects like this.


If you were doing a WaitForSingleObject(), did that call actually fail? Maybe it was throwing the invalid handle error too so it only looked like it was "receiving the event". Also possible that the broken CreateEvent() code was never actually compiled until the RC file was changed. In any case there's no way to tell without seeing the code.

链接地址: http://www.djcxy.com/p/30802.html

上一篇: 可以使用原子<bool>进行多线程同步比事件

下一篇: 使用无效句柄调用SetEvent