 
     dispatch_semaphore_wait(mutex, DISPATCH_TIME_FOREVER)
 
-    while !self.closed &&  elements >= capacity
+    while !self.closed && head+capacity <= tail
     {
       wait(mutex: mutex, queue: writerQueue)
-      dispatch_semaphore_wait(mutex, DISPATCH_TIME_FOREVER)
     }
 
     if self.closed


final class QBufferedNChan<T>: Chan<T>
{
  private let q = PointerQueue<T>()

  // housekeeping variables

  private let capacity: Int

  // PointerQueue keeps count of its stored elements. Unfortunately, calling
  // q.count repeatedly ends up degrading performance noticeably (~50ns/iteration).
  // Keep track locally instead.

  private var elements = 0

  private let readerQueue = ObjectQueue<dispatch_semaphore_t>()
  private let writerQueue = ObjectQueue<dispatch_semaphore_t>()


  override func get() -> T?
  {
    if self.closed && head >= tail { return nil }

    dispatch_semaphore_wait(mutex, DISPATCH_TIME_FOREVER)

    while !self.closed && head >= tail
    {
      wait(mutex: mutex, queue: readerQueue)
    }

    if self.closed && head >= tail
    {
      dispatch_semaphore_signal(mutex)
      return nil
    }

    let element = headptr.move()
    headptr = headptr.successor()
    head += 1
    if (head&mask == 0) { headptr = buffer }

    if writerQueue.count > 0
    {
      dispatch_semaphore_signal(writerQueue.dequeue()!)
    }

    if head < tail && readerQueue.count > 0
    {
      dispatch_semaphore_signal(readerQueue.dequeue()!)
    }

    dispatch_semaphore_signal(mutex)

    return element
  }
}
