import Foundation


///
/// Using class so it can be shared even if
/// it appears to be a field in a class.
///
class Mutex {
    ///
    /// The mutex instance.
    ///
    private let semaphore = DispatchSemaphore(value: 1)

    ///
    /// Running the supplied closure synchronously.
    ///
    /// - Parameter closure: the closure to run
    /// - Returns: the value returned by the closure
    /// - Throws: the exception populated by the closure run
    ///
    @discardableResult
    func synchronized<R>(closure: () throws -> R) rethrows -> R {
        semaphore.wait()
        defer {
            semaphore.signal()
        }
        return try closure()
    }
}

import Foundation


/// 
/// Using class so it can be shared even if
/// it appears to be a field in a class.
/// 
class Mutex {
    
    /// 
    /// The mutex instance.
    /// 
    private var mutex = pthread_mutex_t()
    
    /// 
    /// Initialization
    /// 
    init() {
        pthread_mutex_init(&mutex, nil)
    }
    
    /// 
    /// Running the supplied closure synchronously.
    /// 
    /// - Parameter closure: the closure to run
    /// - Returns: the value returned by the closure
    /// - Throws: the exception populated by the closure run
    /// 
    @discardableResult
    func synchronized<R>(closure: () throws -> R) rethrows -> R {
        pthread_mutex_lock(&mutex)
        defer {
            pthread_mutex_unlock(&mutex)
        }
        return try closure()
    }

    deinit {
        // free the mutex resource
        pthread_mutex_destroy(&mutex)
    }
}

--- 
+++ 
@@ -1,42 +1,29 @@
 import Foundation
 
 
-/// 
+///
 /// Using class so it can be shared even if
 /// it appears to be a field in a class.
-/// 
+///
 class Mutex {
-    
-    /// 
+    ///
     /// The mutex instance.
-    /// 
-    private var mutex = pthread_mutex_t()
-    
-    /// 
-    /// Initialization
-    /// 
-    init() {
-        pthread_mutex_init(&mutex, nil)
-    }
-    
-    /// 
+    ///
+    private let semaphore = DispatchSemaphore(value: 1)
+
+    ///
     /// Running the supplied closure synchronously.
-    /// 
+    ///
     /// - Parameter closure: the closure to run
     /// - Returns: the value returned by the closure
     /// - Throws: the exception populated by the closure run
-    /// 
+    ///
     @discardableResult
     func synchronized<R>(closure: () throws -> R) rethrows -> R {
-        pthread_mutex_lock(&mutex)
+        semaphore.wait()
         defer {
-            pthread_mutex_unlock(&mutex)
+            semaphore.signal()
         }
         return try closure()
     }
-
-    deinit {
-        // free the mutex resource
-        pthread_mutex_destroy(&mutex)
-    }
 }
Use crossplatform semaphore instead of unsafe raw pthread_mutex_t

Also, it seems faster: https://stackoverflow.com/a/46174300/1046374

Signed-off-by: Ivan Kochurkin <7704623aa56c2b72c3121ff876cc07e7c36aec52@gmail.com>
