title: Thread-safe ring buffer for producers-consumer in C
body: <p>In C, I have <strong>several threads producing</strong> <code>long</code> values, and <strong>one thread consuming</strong> them. Therefore I need a buffer of a fixed size implemented in a similar fashion to i.e. the <a href="http://en.wikipedia.org/wiki/Circular_buffer#Difficulties" rel="nofollow">Wikipedia implementation</a>, and methods that access it in a thread-safe manner.</p>
  
  <p>On a general level, the following should hold:</p>
  
  <ul>
  <li>When adding to a full buffer, the thread should be blocked (no overwriting old values).</li>
  <li>The consumer thread should be blocked until the buffer is full - it's job has a high constant cost, and should do as much work as possible. (Does this call for a double-buffered solution?)</li>
  </ul>
  
  <p>I would like to use a tried implementation, preferably from a library. Any ideas?</p>
  
  <hr>
  
  <p>Motivation &amp; explanation:</p>
  
  <p>I am writing JNI code dealing with deleting <a href="http://java.sun.com/docs/books/jni/html/refs.html" rel="nofollow">global references</a> kept as <a href="http://docs.oracle.com/javase/6/docs/platform/jvmti/jvmti.html#Heap" rel="nofollow">tags</a> in heap objects. </p>
  
  <p>When a <code>ObjectFree</code> JVMTI event occurs, I get a <code>long</code> tag representing a global reference I need to free using <code>DeleteGlobalRef</code>. For this, I need a <code>JNIEnv</code> reference - and getting it is <strong>really</strong> costly, so I want to buffer the requests and remove as many as possible at once. </p>
  
  <p>There might be many threads receiving the <code>ObjectFree</code> event, and there will be one thread (mine) doing the reference deletion.</p>