 
 import Darwin.Mach
 import Dispatch.time
+import Foundation.NSThread
 
 struct SemaphorePool
 {

final class ChannelSemaphore
{
  private var svalue: Int32
  private let semp: semaphore_t

  private var currentState = ChannelSemaphoreState.Ready

  private init(value: Int32)
  {
    svalue = (value > 0) ? value : 0
    semp = {
      var newport = semaphore_t()
      let kr = semaphore_create(mach_task_self_, &newport, SYNC_POLICY_FIFO, 0)
      assert(kr == KERN_SUCCESS, __FUNCTION__)
      return newport
    }()
  }

  private convenience init()

    assert(kr == KERN_SUCCESS, __FUNCTION__)
  }

  final private func initSemaphorePort()
  {
    var semaphore = semaphore_t()
    let kr = semaphore_create(mach_task_self_, &semaphore, SYNC_POLICY_FIFO, 0)
    assert(kr == KERN_SUCCESS, __FUNCTION__)

    func atomicAssignPort(port: semaphore_t, assignee: UnsafeMutablePointer<Void>) -> Bool
    { // succeed only if 'semp' is still zero
      return OSAtomicCompareAndSwap32Barrier(0, unsafeBitCast(port, Int32.self),
        UnsafeMutablePointer<Int32>(assignee))
    }

    if !atomicAssignPort(semaphore, &semp)
    { // another initialization attempt succeeded concurrently. Don't leak the port; return it.
      let kr = semaphore_destroy(mach_task_self_, semaphore)
      assert(kr == KERN_SUCCESS, __FUNCTION__)
    }
  }

  var state: ChannelSemaphoreState { return currentState }

  func setState(newState: ChannelSemaphoreState) -> Bool
