title: Concurrency and lock in Swift
body: <h2>Premise</h2>
  
  <p>We all know there are <strong>good numbers</strong> and <strong>bad numbers</strong> in the universe.</p>
  
  <p>I have the following synchronous function </p>
  
  <pre><code>func isGood(number:Int) -&gt; Bool {
      // synchronous connection
      // ...
      // returns a Bool
  }
  </code></pre>
  
  <p>Of course I am not providing the secret implementation here, but you should know that it performs a <strong>synchronous</strong> internet connection and it does return</p>
  
  <ul>
  <li><strong><code>true</code></strong>: if the <code>Int</code> received as param is a "good number"</li>
  <li><strong><code>false</code></strong>: otherwise</li>
  </ul>
  
  <h2>The problem</h2>
  
  <p>Now, given the 100 integers from 0 to 99, I want to know if at least 51 of them are good numbers.</p>
  
  <h2>The synchronous approach</h2>
  
  <p>I could write something like this.</p>
  
  <pre><code>func majorityIsGood() -&gt; Bool {
      var count = 0
      for i in 0...99 {
          if isGood(i) {
              count++
              if count &gt; 50 {
                  return true
              }
          }
      }
      return false
  }
  </code></pre>
  
  <p>But performing 100 (in the worst case scenario) synchronous call to <code>isGood</code> will require too much time. I need the answer as fast as possible.</p>
  
  <h2>The asynchronous approach</h2>
  
  <p>I would prefer something like this</p>
  
  <pre><code>func majorityIsGood(completion:(good:Bool) -&gt; ()) {
      var goodNums = 0
      var badNums = 0
      var resultFound = false
  
      for i in 0...99 {
          dispatch_async(DISPATCH_QUEUE_CONCURRENT) {
  
              let isGood = isGood(i)
  
              // lineA
              // begin lock on (resultFound)
              if !resultFound {
                  if isGood {
                      goodNums++
                  } else {
                      badNums++
                  }
                  if goodNums &gt; 50 || badNums &gt;= 50 {
                      resultFound = true
                      completion(good: goodNums &gt; 50)
                  }
              }
              // end lock on (resultFound)
              // lineB
          }
      }
  }
  </code></pre>
  
  <h2>Questions</h2>
  
  <ol>
  <li>How can I guarantee a <strong>synchronous</strong> access to the block of code between <code>lineA</code> and <code>lineB</code> in Swift?</li>
  <li>And finally, once I get the result, is it possible to <strong>kill</strong> the concurrent closures that are still being processed?</li>
  </ol>
  
  <p>Thank you in advance.</p>