-
-
Save ggrell/6564f87e8753fd39d8cb552969285d13 to your computer and use it in GitHub Desktop.
Atomic way to operate on integers in Swift. Inspired by Java's AtomicInteger
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 Foundation | |
public final class AtomicInteger { | |
private let lock = DispatchSemaphore(value: 1) | |
private var _value: Int | |
public init(value initialValue: Int = 0) { | |
_value = initialValue | |
} | |
public var value: Int { | |
get { | |
lock.wait() | |
defer { lock.signal() } | |
return value | |
} | |
set { | |
lock.wait() | |
defer { lock.signal() } | |
value = newValue | |
} | |
} | |
public func decrementAndGet() -> Int { | |
lock.wait() | |
defer { lock.signal() } | |
value -= 1 | |
return value | |
} | |
public func incrementAndGet() -> Int { | |
lock.wait() | |
defer { lock.signal() } | |
value += 1 | |
return value | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment