             
             let semaphore = self.mutuallyExclusiveSemaphores[categoryName]!
             semaphore.count--
-            group = semaphore.group
+            dispatch_semaphore = semaphore.dispatch_semaphore
             
             if semaphore.count == 0 {
                 self.mutuallyExclusiveSemaphores[categoryName] = nil
             }
         }
         
-        dispatch_group_leave(group)
+        dispatch_semaphore_signal(dispatch_semaphore)
     }
     
 }

    }
    
    private static func wait(categoryName: String) {
        let group: dispatch_group_t?
        
        do {
            withUnsafeMutablePointer(&self.spinlock, OSSpinLockLock)
            defer { withUnsafeMutablePointer(&self.spinlock, OSSpinLockUnlock) }

            group = self.mutuallyExclusiveSemaphores[categoryName]?.group
        }
        
        if let group = group {
            dispatch_group_wait(group, DISPATCH_TIME_FOREVER)
        }
    }
    
    internal static func enter(categoryName: String) {
        let group: dispatch_group_t
        
        withUnsafeMutablePointer(&self.spinlock, OSSpinLockLock)
        defer { withUnsafeMutablePointer(&self.spinlock, OSSpinLockUnlock) }

        if let semaphore = self.mutuallyExclusiveSemaphores[categoryName] {
            semaphore.count++
            group = semaphore.group
        }
        else {
            let semaphore = Semaphore(group: dispatch_group_create(), count: 1)
            self.mutuallyExclusiveSemaphores[categoryName] = semaphore
            group = semaphore.group
        }
        
        dispatch_group_enter(group)
    }
    
    internal static func leave(categoryName: String) {
        let group: dispatch_group_t
        
        do {
            withUnsafeMutablePointer(&self.spinlock, OSSpinLockLock)

import Foundation

private final class Semaphore {
    private let dispatch_semaphore: dispatch_semaphore_t
    private var count: Int
    
    private init(dispatch_semaphore: dispatch_semaphore_t, count: Int) {
        self.dispatch_semaphore = dispatch_semaphore
        self.count = count
    }
}
