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

前端之家收集整理的这篇文章主要介绍了有没有什么办法锁定一个对象在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)
                }
            }

        }
    }
}

猜你在找的Swift相关文章