Last active
July 13, 2017 03:48
-
-
Save paulocoutinhox/cdb1bebb71692e5c435a706b051ce61f to your computer and use it in GitHub Desktop.
AtomicInteger implementation
This file contains hidden or 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