Skip to content

Instantly share code, notes, and snippets.

@dotWasim
Created February 2, 2020 10:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dotWasim/53f1b909ee8fe09fc775038385c363ff to your computer and use it in GitHub Desktop.
Save dotWasim/53f1b909ee8fe09fc775038385c363ff to your computer and use it in GitHub Desktop.
Thread-safe counter using DispatchSemaphore
import XCTest
struct SynchronizedSemaphore<Value> {
private let mutex = DispatchSemaphore(value: 1)
private var _value: Value
init(_ value: Value) {
self._value = value
}
var value: Value {
mutex.lock { _value }
}
mutating func value(execute task: (inout Value) -> Void) {
mutex.lock { task(&_value) }
}
}
private extension DispatchSemaphore {
func lock<T>(execute task: () throws -> T) rethrows -> T {
wait()
defer { signal() }
return try task()
}
}
func test() {
var temp = SynchronizedSemaphore<Int>(0)
temp.value { $0 = 0 } // Reset
DispatchQueue.concurrentPerform(iterations: 1_000) { _ in
temp.value { $0 += 1 }
}
print(temp.value)
XCTAssertEqual(temp.value, 1_000)
}
test()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment