I have the following code:
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)
}
}
}
}
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.
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.
In C# we are able to do something like:
Object lockObject = new Object();
...
lock (lockObject) {
pendingElements--;
if (pendingElements == 0) {
Console.WriteLine(sum);
}
}
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?