栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何在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开始不推荐使用朋友.Xpre8建议改用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 thread
What advantage(s) does dispatch_sync have over
@synchronized? is also very interesting.



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/426970.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号