有没有办法像C#中那样在Swift中锁定对象 [英] Is there any way of locking an object in Swift like in 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
如其名称所示,异步处理其输入参数,并在完成时调用其相应的完成处理程序.
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屋!