有没有什么办法锁定一个对象在Swift像在C#

我有以下代码
func foo() {
    var sum = 0
    var pendingElements = 10

    for i in 0 ..< 10 {
        proccessElementAsync(i) { value in
            sum += value
            pendingElements--

            if pendingElements == 0 {
                println(sum)
            }
        }
    }
}

在这种情况下,函数proccessElementAsync(如其名称所示)异步处理其输入参数,当其完成时,调用其相应的完成处理程序.

这种方法的不便之处在于,由于可通过多个线程访问变量pendingElements,所以可能的是,如果pendingElements == 0的语句永远不会为true.

在C#中,我们可以做一些像:

Object lockObject = new Object();
...

lock (lockObject) {
    pendingElements--;

    if (pendingElements == 0) {
        Console.WriteLine(sum);
    }
}

这样可以确保该变量只能在一个线程的同时被访问.有没有办法在Swift中获得同样的行为?

希望这将有助于您.
func lock(obj: AnyObject,blk:() -> ()) {
    objc_sync_enter(obj)
    blk()
    objc_sync_exit(obj)
}

var pendingElements = 10

func foo() {
    var sum = 0
    var pendingElements = 10

    for i in 0 ..< 10 {
        proccessElementAsync(i) { value in

            lock(pendingElements) {
                sum += value
                pendingElements--

                if pendingElements == 0 {
                    println(sum)
                }
            }

        }
    }
}

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...