如何在Swift中原子地增加一个变量?

mm9b1k5b  于 2023-05-27  发布在  Swift
关注(0)|答案(8)|浏览(123)

我希望能够原子地递增计数器,但我找不到任何关于如何做到这一点的参考。
根据评论添加更多信息:

  • 你在用GCD吗?不,我不用GCD。不得不使用队列系统来增加一个数字似乎有些过分了。
    • 你了解基本的线程安全吗?是的,否则我不会问原子增量。
  • 这个变量是本地的吗?没有
    • 是示例级的吗?* 是的,它应该是单个示例的一部分。

我想做这样的事情:

class Counter {
      private var mux: Mutex
      private (set) value: Int
      func increment() {
          mux.lock()
          value += 1
          mux.unlock()
      }
 }
w6lpcovy

w6lpcovy1#

Low-Level Concurrency APIs
有一个很长的OSAtomicIncrement和OSAtomicDecrement函数列表,它们允许您以原子方式递增和递减整数值-线程安全,而不必采用锁(或使用队列)。如果您需要从多个线程递增全局计数器以进行统计,则这些可能很有用。如果您所做的只是递增一个全局计数器,那么无障碍的OSAtomicIncrement版本就很好,并且当没有争用时,调用它们的成本很低。
这些函数使用固定大小的整数,您可以根据需要选择32位或64位变体:

class Counter {
    private (set) var value : Int32 = 0
    func increment () {
        OSAtomicIncrement32(&value)
    }
}

(**注意:**正如Erik艾格纳正确注意到的,OSAtomicIncrement32和朋友从macOS 10.12/iOS 10.10起已弃用。Xcode 8建议使用<stdatomic.h>中的函数。然而,这似乎很困难,比较Swift 3: atomic_compare_exchange_stronghttps://openradar.appspot.com/27161329。因此,以下基于GCD的方法似乎是目前最好的解决方案。)
或者,可以使用GCD队列进行同步。来自“并发编程指南”中的Dispatch Queues:
使用调度队列,您可以将两个任务都添加到串行调度队列,以确保在任何给定时间只有一个任务修改资源。这种基于队列的同步比锁更有效,因为锁在有竞争和无竞争的情况下总是需要昂贵的内核陷阱,而分派队列主要在应用程序的进程空间中工作,只有在绝对必要时才向下调用内核。
对你来说

// Swift 2:
class Counter {
    private var queue = dispatch_queue_create("your.queue.identifier", DISPATCH_QUEUE_SERIAL)
    private (set) var value: Int = 0

    func increment() {
        dispatch_sync(queue) {
            value += 1
        }
    }
}

// Swift 3:
class Counter {
    private var queue = DispatchQueue(label: "your.queue.identifier") 
    private (set) var value: Int = 0

    func increment() {
        queue.sync {
            value += 1
        }
    }
}

请参阅Adding items to Swift array across multiple threads causing issues (because arrays aren't thread safe) - how do I get around that?GCD with static functions of a struct以获取更复杂的示例。这个线程What advantage(s) does dispatch_sync have over @synchronized?也很有趣。

u59ebvdq

u59ebvdq2#

在这种情况下,队列是一种多余的东西。您可以使用Swift 3中引入的DispatchSemaphore来实现此目的,如下所示:

import Foundation

public class AtomicInteger {

    private let lock = DispatchSemaphore(value: 1)
    private var value = 0

    // You need to lock on the value when reading it too since
    // there are no volatile variables in Swift as of today.
    public func get() -> Int {

        lock.wait()
        defer { lock.signal() }
        return value
    }

    public func set(_ newValue: Int) {

        lock.wait()
        defer { lock.signal() }
        value = newValue
    }

    public func incrementAndGet() -> Int {

        lock.wait()
        defer { lock.signal() }
        value += 1
        return value
    }
}

类的最新版本是over here

luaexgnf

luaexgnf3#

我知道这个问题已经有点老了,但我最近才偶然发现了同样的问题。在研究了一点并阅读了像http://www.cocoawithlove.com/blog/2016/06/02/threads-and-mutexes.html这样的帖子之后,我想出了这个原子计数器的解决方案。也许它也会帮助其他人。

import Foundation

class AtomicCounter {

  private var mutex = pthread_mutex_t()
  private var counter: UInt = 0

  init() {
    pthread_mutex_init(&mutex, nil)
  }

  deinit {
    pthread_mutex_destroy(&mutex)
  }

  func incrementAndGet() -> UInt {
    pthread_mutex_lock(&mutex)
    defer {
      pthread_mutex_unlock(&mutex)
    }
    counter += 1
    return counter
  }
}
emeijp43

emeijp434#

详情

  • Xcode 10.1(10B61)
  • Swift 4.2

解决方案

import Foundation

struct AtomicInteger<Type>: BinaryInteger where Type: BinaryInteger {

    typealias Magnitude = Type.Magnitude
    typealias IntegerLiteralType = Type.IntegerLiteralType
    typealias Words = Type.Words
    fileprivate var value: Type

    private var semaphore = DispatchSemaphore(value: 1)
    fileprivate func _wait() { semaphore.wait() }
    fileprivate func _signal() { semaphore.signal() }

    init() { value = Type() }

    init(integerLiteral value: AtomicInteger.IntegerLiteralType) {
        self.value = Type(integerLiteral: value)
    }

    init<T>(_ source: T) where T : BinaryInteger {
        value = Type(source)
    }

    init(_ source: Int) {
        value = Type(source)
    }

    init<T>(clamping source: T) where T : BinaryInteger {
        value = Type(clamping: source)
    }

    init?<T>(exactly source: T) where T : BinaryInteger {
        guard let value = Type(exactly: source) else { return nil }
        self.value = value
    }

    init<T>(truncatingIfNeeded source: T) where T : BinaryInteger {
        value = Type(truncatingIfNeeded: source)
    }

    init?<T>(exactly source: T) where T : BinaryFloatingPoint {
        guard let value = Type(exactly: source) else { return nil }
        self.value = value
    }

    init<T>(_ source: T) where T : BinaryFloatingPoint {
        value = Type(source)
    }
}

// Instance Properties

extension AtomicInteger {
    var words: Type.Words {
        _wait(); defer { _signal() }
        return value.words
    }
    var bitWidth: Int {
        _wait(); defer { _signal() }
        return value.bitWidth
    }
    var trailingZeroBitCount: Int {
        _wait(); defer { _signal() }
        return value.trailingZeroBitCount
    }
    var magnitude: Type.Magnitude {
        _wait(); defer { _signal() }
        return value.magnitude
    }
}

// Type Properties

extension AtomicInteger {
    static var isSigned: Bool { return Type.isSigned }
}

// Instance Methods

extension AtomicInteger {

    func quotientAndRemainder(dividingBy rhs: AtomicInteger<Type>) -> (quotient: AtomicInteger<Type>, remainder: AtomicInteger<Type>) {
        _wait(); defer { _signal() }
        rhs._wait(); defer { rhs._signal() }
        let result = value.quotientAndRemainder(dividingBy: rhs.value)
        return (AtomicInteger(result.quotient), AtomicInteger(result.remainder))
    }

    func signum() -> AtomicInteger<Type> {
        _wait(); defer { _signal() }
        return AtomicInteger(value.signum())
    }
}

extension AtomicInteger {

    fileprivate static func atomicAction<Result, Other>(lhs: AtomicInteger<Type>,
                                                        rhs: Other, closure: (Type, Type) -> (Result)) -> Result where Other : BinaryInteger {
        lhs._wait(); defer { lhs._signal() }
        var rhsValue = Type(rhs)
        if let rhs = rhs as? AtomicInteger {
            rhs._wait(); defer { rhs._signal() }
            rhsValue = rhs.value
        }
        let result = closure(lhs.value, rhsValue)
        return result
    }

    fileprivate static func atomicActionAndResultSaving<Other>(lhs: inout AtomicInteger<Type>,
                                                               rhs: Other, closure: (Type, Type) -> (Type)) where Other : BinaryInteger {
        lhs._wait(); defer { lhs._signal() }
        var rhsValue = Type(rhs)
        if let rhs = rhs as? AtomicInteger {
            rhs._wait(); defer { rhs._signal() }
            rhsValue = rhs.value
        }
        let result = closure(lhs.value, rhsValue)
        lhs.value = result
    }
}

// Math Operator Functions

extension AtomicInteger {

    static func != <Other>(lhs: AtomicInteger, rhs: Other) -> Bool where Other : BinaryInteger {
        return atomicAction(lhs: lhs, rhs: rhs) { $0 != $1 }
    }

    static func != (lhs: AtomicInteger, rhs: AtomicInteger) -> Bool {
        return atomicAction(lhs: lhs, rhs: rhs) { $0 != $1 }
    }

    static func % (lhs: AtomicInteger, rhs: AtomicInteger) -> AtomicInteger {
        let value = atomicAction(lhs: lhs, rhs: rhs) { $0 % $1 }
        return self.init(value)
    }

    static func %= (lhs: inout AtomicInteger, rhs: AtomicInteger) {
        atomicActionAndResultSaving(lhs: &lhs, rhs: rhs) { $0 % $1 }
    }

    static func & (lhs: AtomicInteger, rhs: AtomicInteger) -> AtomicInteger {
        let value = atomicAction(lhs: lhs, rhs: rhs) { $0 & $1 }
        return self.init(value)
    }

    static func &= (lhs: inout AtomicInteger, rhs: AtomicInteger) {
        atomicActionAndResultSaving(lhs: &lhs, rhs: rhs) { $0 & $1 }
    }

    static func * (lhs: AtomicInteger, rhs: AtomicInteger) -> AtomicInteger {
        let value = atomicAction(lhs: lhs, rhs: rhs) { $0 * $1 }
        return self.init(value)
    }

    static func *= (lhs: inout AtomicInteger, rhs: AtomicInteger) {
        atomicActionAndResultSaving(lhs: &lhs, rhs: rhs) { $0 * $1 }
    }

    static func + (lhs: AtomicInteger, rhs: AtomicInteger) -> AtomicInteger {
        let value = atomicAction(lhs: lhs, rhs: rhs) { $0 + $1 }
        return self.init(value)
    }
    static func += (lhs: inout AtomicInteger, rhs: AtomicInteger) {
        atomicActionAndResultSaving(lhs: &lhs, rhs: rhs) { $0 + $1 }
    }

    static func - (lhs: AtomicInteger, rhs: AtomicInteger) -> AtomicInteger {
        let value = atomicAction(lhs: lhs, rhs: rhs) { $0 - $1 }
        return self.init(value)
    }

    static func -= (lhs: inout AtomicInteger, rhs: AtomicInteger) {
        atomicActionAndResultSaving(lhs: &lhs, rhs: rhs) { $0 - $1 }
    }

    static func / (lhs: AtomicInteger, rhs: AtomicInteger) -> AtomicInteger {
        let value = atomicAction(lhs: lhs, rhs: rhs) { $0 / $1 }
        return self.init(value)
    }

    static func /= (lhs: inout AtomicInteger, rhs: AtomicInteger) {
        atomicActionAndResultSaving(lhs: &lhs, rhs: rhs) { $0 / $1 }
    }
}

// Shifting Operator Functions

extension AtomicInteger {
    static func << <RHS>(lhs:  AtomicInteger<Type>, rhs: RHS) -> AtomicInteger where RHS : BinaryInteger {
        let value = atomicAction(lhs: lhs, rhs: rhs) { $0 << $1 }
        return self.init(value)
    }

    static func <<= <RHS>(lhs: inout AtomicInteger, rhs: RHS) where RHS : BinaryInteger {
        atomicActionAndResultSaving(lhs: &lhs, rhs: rhs) { $0 << $1 }
    }

    static func >> <RHS>(lhs: AtomicInteger, rhs: RHS) -> AtomicInteger where RHS : BinaryInteger {
        let value = atomicAction(lhs: lhs, rhs: rhs) { $0 >> $1 }
        return self.init(value)
    }

    static func >>= <RHS>(lhs: inout AtomicInteger, rhs: RHS) where RHS : BinaryInteger {
        atomicActionAndResultSaving(lhs: &lhs, rhs: rhs) { $0 >> $1 }
    }
}

// Comparing Operator Functions

extension AtomicInteger {

    static func < <Other>(lhs: AtomicInteger<Type>, rhs: Other) -> Bool where Other : BinaryInteger {
        return atomicAction(lhs: lhs, rhs: rhs) { $0 < $1 }
    }

    static func <= (lhs: AtomicInteger, rhs: AtomicInteger) -> Bool {
        return atomicAction(lhs: lhs, rhs: rhs) { $0 <= $1 }
    }

    static func == <Other>(lhs: AtomicInteger, rhs: Other) -> Bool where Other : BinaryInteger {
        return atomicAction(lhs: lhs, rhs: rhs) { $0 == $1 }
    }

    static func > <Other>(lhs: AtomicInteger, rhs: Other) -> Bool where Other : BinaryInteger {
        return atomicAction(lhs: lhs, rhs: rhs) { $0 > $1 }
    }

    static func > (lhs: AtomicInteger, rhs: AtomicInteger) -> Bool {
        return atomicAction(lhs: lhs, rhs: rhs) { $0 > $1 }
    }

    static func >= (lhs: AtomicInteger, rhs: AtomicInteger) -> Bool {
        return atomicAction(lhs: lhs, rhs: rhs) { $0 >= $1 }
    }

    static func >= <Other>(lhs: AtomicInteger, rhs: Other) -> Bool where Other : BinaryInteger {
        return atomicAction(lhs: lhs, rhs: rhs) { $0 >= $1 }
    }
}

// Binary Math Operator Functions

extension AtomicInteger {

    static func ^ (lhs: AtomicInteger, rhs: AtomicInteger) -> AtomicInteger {
        let value = atomicAction(lhs: lhs, rhs: rhs) { $0 ^ $1 }
        return self.init(value)
    }

    static func ^= (lhs: inout AtomicInteger, rhs: AtomicInteger) {
        atomicActionAndResultSaving(lhs: &lhs, rhs: rhs) { $0 ^ $1 }
    }

    static func | (lhs: AtomicInteger, rhs: AtomicInteger) -> AtomicInteger {
        let value = atomicAction(lhs: lhs, rhs: rhs) { $0 | $1 }
        return self.init(value)
    }

    static func |= (lhs: inout AtomicInteger, rhs: AtomicInteger) {
        atomicActionAndResultSaving(lhs: &lhs, rhs: rhs) { $0 | $1 }
    }

    static prefix func ~ (x: AtomicInteger) -> AtomicInteger {
        x._wait(); defer { x._signal() }
        return self.init(x.value)
    }
}

// Hashable

extension AtomicInteger {

    var hashValue: Int {
        _wait(); defer { _signal() }
        return value.hashValue
    }

    func hash(into hasher: inout Hasher) {
        _wait(); defer { _signal() }
        value.hash(into: &hasher)
    }
}

// Get/Set

extension AtomicInteger {

    // Single  actions

    func get() -> Type {
        _wait(); defer { _signal() }
        return value
    }

    mutating func set(value: Type) {
        _wait(); defer { _signal() }
        self.value = value
    }

    // Multi-actions

    func get(closure: (Type)->()) {
        _wait(); defer { _signal() }
        closure(value)
    }

    mutating func set(closure: (Type)->(Type)) {
        _wait(); defer { _signal() }
        self.value = closure(value)
    }
}

用法

// Usage Samples
let numA = AtomicInteger<Int8>(0)
let numB = AtomicInteger<Int16>(0)
let numC = AtomicInteger<Int32>(0)
let numD = AtomicInteger<Int64>(0)

var num1 = AtomicInteger<Int>(0)
num1 += 1
num1 -= 1
num1 = 10
num1 = num1/2

var num2 = 0
num2 = num1.get()
num1.set(value: num2*5)

// lock num1 to do several actions
num1.get { value in
    //...
}

num1.set { value in
    //...
    return value
}

完整样本

import Foundation

var x = AtomicInteger<Int>(0)
let dispatchGroup = DispatchGroup()
private func async(dispatch: DispatchQueue, closure: @escaping (DispatchQueue)->()) {
    for _ in 0 ..< 100 {
        dispatchGroup.enter()
        dispatch.async {
            print("Queue: \(dispatch.qos.qosClass)")
            closure(dispatch)
            dispatchGroup.leave()
        }
    }
}

func sample() {
    let closure1: (DispatchQueue)->() = { _ in x += 1 }
    let closure2: (DispatchQueue)->() = { _ in x -= 1 }
    async(dispatch: .global(qos: .userInitiated), closure: closure1) // result: x += 100
    async(dispatch: .global(qos: .utility), closure: closure1) // result: x += 100
    async(dispatch: .global(qos: .background), closure: closure2) // result: x -= 100
    async(dispatch: .global(qos: .default), closure: closure2) // result: x -= 100
}

sample()
dispatchGroup.wait()
print(x) // expected result x = 0
x7rlezfr

x7rlezfr5#

我改进了@florian的答案,使用了一些重载运算符:

import Foundation

class AtomicInt {

    private var mutex = pthread_mutex_t()
    private var integer: Int = 0
    var value : Int {
        return integer
    }

    //MARK: - lifecycle

    init(_ value: Int = 0) {
        pthread_mutex_init(&mutex, nil)
        integer = value
    }

    deinit {
        pthread_mutex_destroy(&mutex)
    }

    //MARK: - Public API

    func increment() {
        pthread_mutex_lock(&mutex)
        defer {
            pthread_mutex_unlock(&mutex)
        }
        integer += 1
    }

    func incrementAndGet() -> Int {
        pthread_mutex_lock(&mutex)
        defer {
            pthread_mutex_unlock(&mutex)
        }
        integer += 1
        return integer
    }

    func decrement() {
        pthread_mutex_lock(&mutex)
        defer {
            pthread_mutex_unlock(&mutex)
        }
        integer -= 1
    }

    func decrementAndGet() -> Int {
        pthread_mutex_lock(&mutex)
        defer {
            pthread_mutex_unlock(&mutex)
        }
        integer -= 1
        return integer
    }

    //MARK: - overloaded operators

   static func > (lhs: AtomicInt, rhs: Int) -> Bool {
        return lhs.integer > rhs
    }

    static func < (lhs: AtomicInt, rhs: Int) -> Bool {
        return lhs.integer < rhs
    }

    static func == (lhs: AtomicInt, rhs: Int) -> Bool {
        return lhs.integer == rhs
    }

    static func > (lhs: Int, rhs: AtomicInt) -> Bool {
        return lhs > rhs.integer
    }

    static func < (lhs: Int, rhs: AtomicInt) -> Bool {
        return lhs < rhs.integer
    }

    static func == (lhs: Int, rhs: AtomicInt) -> Bool {
        return lhs == rhs.integer
    }

    func test() {
        let atomicInt = AtomicInt(0)
        atomicInt.increment()
        atomicInt.decrement()
        if atomicInt > 10  { print("bigger than 10") }
        if atomicInt < 10  { print("smaller than 10") }
        if atomicInt == 10 { print("its 10") }
        if 10 > atomicInt  { print("10 is bigger") }
        if 10 < atomicInt  { print("10 is smaller") }
        if 10 == atomicInt { print("its 10") }
    }

}
ffscu2ro

ffscu2ro6#

Swift Atomic
您可以查看Apple托管的Swift Atomics库,它支持一般类型
Concurrency theory(https://stackoverflow.com/a/59491099/4770877)

rnmwe5a2

rnmwe5a27#

您可以使用@propertyWrapper s来完成此操作

import Foundation

@propertyWrapper
class Atomic<Value> where Value: BinaryInteger {

    private let lock: NSLock
    private var value: Value

    init(default: Value) {
        self.lock = NSLock()
        self.value = `default`
    }

    var wrappedValue: Value {
        get {
            lock.lock()
            defer { lock.unlock() }
            return value
        }
        set {
            lock.lock()
            value = newValue
            lock.unlock()
        }
    }

    var projectedValue: Atomic<Value> { self }

    func add(_ value: Value) {
        lock.lock()
        self.value += value
        lock.unlock()
    }
}

你可以像这样使用它来原子地递增

class Foo {

    @Atomic(default: 1)
    var counter: Int
}

let foo = Foo()
foo.$counter.add(3)

如果您想包含一个外部库,请使用Swift Atomics

enyaitl3

enyaitl38#

我们可以使用各种方法来原子地增加swift中的变量,并且已经讨论过here
此外,Swift还提出了一个SE-0283提案,在Swift中添加原子变量。

相关问题