您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

如何在Swift中自动递增变量?

如何在Swift中自动递增变量?

来自低级并发API

OSAtomicIncrement和OSAtomicDecrement函数的清单很长,它们使您能够以原子方式递增和递减整数值–线程安全,而不必获取锁(或使用队列)。如果您需要从多个线程中增加全局计数器以进行统计,这些功能将很有用。如果您要做的只是增加一个全局计数器,那么无障碍的OSAtomicIncrement版本就可以了,并且在没有争用时,调用它们很便宜。

这些函数与固定大小的整数一起使用,您可以根据需要选择32位或64位变体:

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

( 正如Erik Aigner所正确注意到的OSAtomicIncrement32那样,从macOS 10.12 / iOS 10.10开始不推荐使用朋友.Xcode8建议改用from的函数<stdatomic.h>。但是这似乎很困难,请比较一下[Swift3:atomic_compare_exchange_strong]和https://openradar.appspot .com / 27161329,因此以下基于GCD的方法现在似乎是最好的解决方案。)

或者,可以使用GCD队列进行同步。从“并发编程指南”中的调度队列中:

…使用调度队列,您可以将两个任务都添加到串行调度队列中,以确保在任何给定时间只有一个任务修改了资源。这种类型的基于队列的同步比锁更有效,因为在有争议和无争议的情况下,锁总是需要昂贵的内核陷阱,而分派队列主要在应用程序的进程空间中工作,并且仅在绝对必要时才调用内核。

在你的情况下

// 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
        }
    }
}

See Adding items to Swift array across multiple threads causing issues (because arrays aren’t thread safe) - how do I get around that? or GCD with static functions of a struct for more sophisticated examples. This threadWhat advantage(s) does dispatch_sync have over @synchronized? is also very interesting.

Swift 2022/1/1 18:13:42 有702人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶