我希望能够以原子方式递增计数器,但我找不到任何关于如何进行的参考.

根据 comments 添加更多信息:

  • 你在用GCD吗?不,我没有使用GCD.必须使用队列系统来增加一个数字似乎有些过分.
  • Do你了解基本的线程安全吗?是的,否则我就不会问原子增量了.
  • 这个变量是局部变量吗?不
  • Is it instance level?是的,它应该是单个实例的一部分.

我想这样做:

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

推荐答案

Low-Level Concurrency APIs开始:

有一长串的OSAtomicIncrement和OsatomicDecretion

这些函数使用固定大小的整数,您可以 Select

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

(Note:正如埃里克·艾格纳正确地注意到的,OSAtomicIncrement32

或者,可以使用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.

Swift相关问答推荐

使SCNode透明,以便您通过它查看其他 node

是否有一个Kotlin等价的Swift s @ AddendableReport注释'

以编程方式使UIView居中,而不影响UIKit中其他UI类的位置

NavigationLink和ObservableObject的动画片段

如何增加 NSStatusBar 图像大小?

为什么Swift可以在没有足够信息的情况下推断类型?

UIBezierPath() 和 DragGesture:连接点创建角而不是曲线

Swift iOS:确定贝塞尔曲线路径是否与 UIView 框架相交?

在 init(from decoder: Decoder) 方法中访问原始 JSON 数据

如何使一个 Reality Composer 场景中的分组对象可拖动?

如何获得不同的插入和移除过渡动画?

如何在 Swift 中将 XPC 自定义类列入白名单?

使用 Date.ParseStrategy 将字符串解析为日期

在 Swift 中从 HTML 生成带有图像的 PDF 而不显示打印界面

Swift 2 或 3 中的 Google Analytics 问题

如何在Swift中找出字母是字母数字还是数字

无法停止 AVPlayer

修复 Swift 3 中的警告C-style for Statement is deprecated

如何在 Swift 中判断变量的类型

'类 'className' 的 NSManagedObject 必须具有有效的 NSEntityDescription.错误