有没有办法像C#中那样在Swift中锁定对象 [英] Is there any way of locking an object in Swift like in C#

查看:75
本文介绍了有没有办法像C#中那样在Swift中锁定对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

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如其名称所示,异步处理其输入参数,并在完成时调用其相应的完成处理程序.

In this case the function proccessElementAsync, as its name indicates, process its input parameter asynchronously and when it finishes it calls its corresponding completion handler.

此方法的不便之处在于,由于变量pendingElements是通过多个线程访问的,因此语句if pendingElements == 0永远不会具有值true.

The inconvenience with this approach is that since the variable pendingElements is accessed through multiple threads, then it is possible that the statement if pendingElements == 0 will never has value true.

在C#中,我们可以执行以下操作:

In C# we are able to do something like:

Object lockObject = new Object();
...

lock (lockObject) {
    pendingElements--;

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

,这确保了只能同时为一个线程访问此变量.有什么办法可以在Swift中获得相同的行为?

and this ensures that this variable will be accessed only for a thread at the same time. Is there any way of getting the same behavior in Swift?

推荐答案

希望这会对您有所帮助.

Hope this will help you.

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

        }
    }
}

这篇关于有没有办法像C#中那样在Swift中锁定对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆