title: Linux synchronization without polling
body: <p>In principle what I want is very simple.</p>
  
  <p>Two executables <code>./read</code> and <code>./write</code> respectively read and write from a resource (let's say a file). Using <code>flock(2)</code> it is easy to prevent race conditions between arbitrary invocations of <code>./read</code> and <code>./write</code> at arbitrary times.</p>
  
  <p>The requirement is that each invocation of <code>./read</code> contains a snapshot of the resource from a previous invocation, and if the current resource matches the snapshot, <code>./read</code> should wait (sleep) until an invocation of <code>./write</code> changes the resource.</p>
  
  <p>From what I gather, the program flows of each program should be something like:</p>
  
  <pre><code>//read.c
  obtain mutex0
    read resource
    is resource same as our snapshot?
      release mutex0 [1]
      sleep until ./write says to wake up [2]
      obtain mutex0
      read resource
    do something with resource
  release mutex0
  
  //write.c
  obtain mutex0
    change resource in some way
    tell any sleeping ./read's to wake up
  release mutex0
  </code></pre>
  
  <p>The main problem with this approach is that there is a tangible delay between the lines labelled <code>[1]</code> and <code>[2]</code>. This means that a <code>./read</code> can release <code>mutex0</code> at <code>[1]</code>, an entire invocation of <code>./write</code> can complete, and then <code>[2]</code> executes, but will stall indefinitely because <code>./write</code> already tried to wake up any sleeping <code>./read</code>s before.</p>
  
  <p>Is there no easy way to do what I want, besides using an entire separate full-blown server process? Also, for those curious I want to do this for an application in CGI.</p>