title: Windows: Using events for shared memory synchronization
body: <p>I am using events to synchronize two processes who access shared memory. What I want to achieve looks like this:</p>
  
  <p>Process A: Signal event for process B</p>
  
  <p>Process A: Wait until process B replies</p>
  
  <p>Process B: Receive event, do memory operation</p>
  
  <p>Process B: Signal event for process A</p>
  
  <p>Process B: Wait until process A replies</p>
  
  <p>In summary I have two processes who are supposed to alternately access shared memory while making sure that they only act after they received a signal from the other process.</p>
  
  <p>Here is how I create the event (it's created in the kernel and shared between a driver and a usermode program):</p>
  
  <pre><code>ZwCreateEvent(&amp;hEvent, EVENT_ALL_ACCESS, &amp;oa, SynchronizationEvent, FALSE);
  </code></pre>
  
  <p>Here is how I open the event in the usermode program:</p>
  
  <pre><code>HANDLE ghWriteEvent = OpenEvent(EVENT_MODIFY_STATE, FALSE, TEXT("Global\\WriteEvent01"));
  </code></pre>
  
  <p>This is how I currently signal the event in the usermode:</p>
  
  <pre><code>SetEvent(ghWriteEvent);
  ResetEvent(ghWriteEvent);
  WaitForSingleObject(ghWriteEvent, INFINITE);
  </code></pre>
  
  <p>This is how I signal the even in the kernel:</p>
  
  <pre><code>KeSetEvent(kEvent, LOW_REALTIME_PRIORITY, FALSE);
  KeResetEvent(kEvent);
  KeWaitForSingleObject(kEvent, Executive, KernelMode, TRUE, NULL);
  </code></pre>
  
  <p>I use SetEvent() so the other process is signaled and ResetEvent() afterwards so that WaitForSingleObject() only succeeds when it receives a signal from the other process.</p>
  
  <p>Is this the correct way of synchronizing two processes? I am not sure since this does work 90% of the time but sometimes it doesn't. </p>
  
  <p>E.g. it works when I print stuff to the console after calling WaitForSingleObject(). When I remove the print the synchronization sometimes fails. This makes me believe that there needs to be a certain delay between the synchronization calls.</p>
  
  <p>Is there an obvious mistake I have overlooked? Thank you.</p>