title: Is there any way of locking an object in Swift like in C#
body: <p>I have the following code:</p>
  
  <pre><code>func foo() {
      var sum = 0
      var pendingElements = 10
  
      for i in 0 ..&lt; 10 {
          proccessElementAsync(i) { value in
              sum += value
              pendingElements--
  
              if pendingElements == 0 {
                  println(sum)
              }
          }
      }
  }
  </code></pre>
  
  <p>In this case the function <code>proccessElementAsync</code>, as its name indicates, process its input parameter asynchronously and when it finishes it calls its corresponding completion handler.</p>
  
  <p>The inconvenience with this approach is that since the variable <code>pendingElements</code> is accessed through multiple threads, then it is possible that the statement <code>if pendingElements == 0</code> will never has value true.</p>
  
  <p>In C# we are able to do something like:</p>
  
  <pre><code>Object lockObject = new Object();
  ...
  
  lock (lockObject) {
      pendingElements--;
  
      if (pendingElements == 0) {
          Console.WriteLine(sum);
      }
  }
  </code></pre>
  
  <p>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?</p>