Question

I have an Manual reset event to control (pause and resume) the while loop. So in the loop, I must continuously check for event signal state

void my_loop()
{
    while(is_ok)
    {
        // Check whether event is in signaled state
        dwWaitResult = WaitForSingleObject( 
            ghEvent, // event handle
            INFINITE);    // indefinite wait

        switch (dwWaitResult) 
        {
            // Event object was signaled
        case WAIT_OBJECT_0: 
            printf("my_loop is working");
            break; 

            // An error occurred
        default: 
            printf("my_loop is halted");
            break;
        }

    }
}

Is this good practice? Does continuously calling WaitForSingleObject cause any problem (CPU, memory, ...) ?

Or are there better ways to check for event state in this case ?

Was it helpful?

Solution

Choosing a manual resest event here causes the loop to be busy (100% cpu) while the event is set. So there must another part in your code resetting the event or did you just forget to reset the event at the WAIT_OBJECT_0 case?

Is this good practice? Well, when the event isn't set, this code is just waiting (INFINITE). However, when the event is set, this is just busy polling for the event to get reset. I suspect you want to do something else in the WAIT_OBJECT_0 case and you want to have external control. You can do it that way, there is no problem using WaitForSingleObjectin a loop.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top