Skip to content

Instantly share code, notes, and snippets.

@paulocoutinhox
Last active July 13, 2017 03:48
Show Gist options
  • Select an option

  • Save paulocoutinhox/cdb1bebb71692e5c435a706b051ce61f to your computer and use it in GitHub Desktop.

Select an option

Save paulocoutinhox/cdb1bebb71692e5c435a706b051ce61f to your computer and use it in GitHub Desktop.
AtomicInteger implementation
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