简体   繁体   中英

WaitForSingleObject - Once per thread

I have one program that sends a signal using this code:

hEvent = CreateEvent(NULL, FALSE, FALSE, szEventName);
...
SetEvent(hEvent);

And I have 4 programs that waits for this signal and calls a function:

while(true) {
    switch (WaitForSingleObject(hEvent, 1000)) {
        case WAIT_OBJECT_0:
               doStuff();
        break;
    }
}

The problem is whenver one of the programs catches the signal using WaitForSingleObject, the other clients doesn't get it! (Only one of the programs, randomly, gets the signal)

Is there a way to make sure all 4 of my programs receives the signal?

The 2nd parameter "FALSE" generated an auto-reset event. You need a manual-reset Event by specifying TRUE in parameter 2:

hEvent = CreateEvent(NULL, TRUE, FALSE, szEventName);

Notice the 2nd parameter of CreateEvent:

HANDLE WINAPI CreateEvent(
  _In_opt_ LPSECURITY_ATTRIBUTES lpEventAttributes,
  _In_     BOOL                  bManualReset,
  _In_     BOOL                  bInitialState,
  _In_opt_ LPCTSTR               lpName
);

Easy if you only need to fire it once, but if you need to fire it multiple times you need to work out how to reset it by having the depending apps send a notice back to the source so it knows all 4 have received it.

More info from the API docs:

"When the state of a manual-reset event object is signaled, it remains signaled until it is explicitly reset to nonsignaled by the ResetEvent function. Any number of waiting threads, or threads that subsequently begin wait operations for the specified event object, can be released while the object's state is signaled.

When the state of an auto-reset event object is signaled, it remains signaled until a single waiting thread is released; the system then automatically resets the state to nonsignaled. If no threads are waiting, the event object's state remains signaled."

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM