Note that there are some explanatory texts on larger screens.

plurals
  1. POUnpredictable behavior with SetEvent and WaitForMultipleObjects
    text
    copied!<p>I am attempting to use <code>SetEvent</code> and <code>WaitForMultipleObjects</code> so I wrote a couple of functions that I wanted to synchronize using Events. I want the first function to execute, and then signal the second function to execute, which in turn signals the first function to execute again etc. </p> <p>Two events were created, one initialized to a signaled state, the other unsignaled. The only way I can get the execution to flow as expected is when putting the each thread to sleep for 10 ms. I read about some caveats about using SetEvent: <a href="http://cboard.cprogramming.com/windows-programming/100818-setevent-resetevent-3.html" rel="nofollow">http://cboard.cprogramming.com/windows-programming/100818-setevent-resetevent-3.html</a></p> <p>My question is must I put my threads to sleep because these function calls require extra time to actually signal the events? When debugging sometimes an event that is set still remains unsignalled. I verify this using process explorer. My code basically looks like this:</p> <p>in the main:</p> <pre><code>//1. FinCalcpidUpdatestruct &lt;&lt; initialize to unsignalled //2. FinUpdatestructCalcpid &lt;&lt; initialize to signalled FinCalcpidUpdatestruct = CreateEvent (NULL, FALSE, FALSE, TEXT("FinCalcpidUpdatestruct")); FinUpdatestructCalcpid = CreateEvent (NULL, FALSE, TRUE, TEXT ("FinUpdatestructCalcpid")); void function1() { int n; int noGoCode; n=0; noGoCode = 0; while(1) { //Sleep(10); noGoCode = WaitForSingleObject (FinCalcpidUpdatestruct, INFINITE); if (noGoCode == WAIT_OBJECT_0) { //wait for FinCalcpidUpdatestruct to be signalled BufferOut[n] = pid_data_array -&gt; output; //signal FinUpdatestructCalcpid if(!SetEvent (FinUpdatestructCalcpid)) printf("Couldn't set the event FinUpdatestructCalcpid\n"); else{ printf("FinUpdatestructCalcpid event set\n"); Sleep(10); } } else printf("error\n"); } } void function2() { int nGoCode = 0; while(1) { //wait for FinUpdatestructCalcpid to be signalled // Sleep(10); nGoCode = WaitForSingleObject (FinUpdatestructCalcpid, INFINITE); if (nGoCode == WAIT_OBJECT_0) { if(!SetEvent (FinCalcpidUpdatestruct)) printf("Couldn't set the event FinCalcpidUpdatestruct\n"); else{ printf("FinCalcpidUpdatestruct event set\n"); Sleep(10); } } else printf("error\n"); }//end while(1) </code></pre> <p>If the sleep is not used then sometimes the same function will run through the while loop a couple of times instead of ping ponging back and forth between the two functions. Any ideas?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload