Created
February 2, 2020 10:56
-
-
Save dotWasim/53f1b909ee8fe09fc775038385c363ff to your computer and use it in GitHub Desktop.
Thread-safe counter using DispatchSemaphore
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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