有没有什么办法锁定一个对象在Swift像在C#
发布时间:2020-12-14 05:40:09 所属栏目:百科 来源:网络整理
导读:我有以下代码: 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(如其
我有以下代码:
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) } } } } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |