title: Strategy for waiting for two near-synchronous events
body: <p>I have a library that I'm writing which processes keystroke events using the Win32 API. Every time a keystroke happens, two separate events occur almost simultaneously (<a href="http://msdn.microsoft.com/en-us/library/ms644984%28v=VS.85%29.aspx" rel="nofollow noreferrer">this</a> and <a href="http://msdn.microsoft.com/en-us/library/ms645600%28v=VS.85%29.aspx" rel="nofollow noreferrer">this</a>). In my library I have two seperate threads, one for each kind of event (hook and raw).</p>
  <p>Thread 1 (hook) waits on Thread 2 (raw) to get its data before it proceeds. It currently uses a barrier-like mechanism to achieve this. So both events must come in before either one is actually processed. So far so good.</p>
  <p>But there's a problem (of course). In an ideal world, I'd be guaranteed to get both events all the time. Unfortunately for reasons I don't understand, sometimes Windows decides not to deliver ONE of the two events to me (often times another app temporarily is screwing with the input). And so if I type &quot;Hello world&quot;, Thread 1 may be processing &quot;H&quot; while Thread 2 may have never gotten the &quot;H&quot; event, and skips to &quot;e&quot;. So the events get out of sync and all hell breaks loose.</p>
  <p>Basically what I'd like is this: I want to pair the events in a way that makes sense. If Thread 1 gets an &quot;H&quot; event, and Thread 2 gets an &quot;e&quot;, it should either (1) try to wait for the correct &quot;H&quot; event, or (2) time out (yes, Thread 1 can gracefully fail if it has to). Since I know that the events should both be coming in within a certain time window, I suppose that makes this a real-time programming task.</p>
  <p>I know positively nothing about real-time programming. Are there already solutions / data structures for this? If so, what are they? If not, what would the general approach be for this type of problem (keeping two temporally close events in sync)?</p>
  <p>Thanks.</p>