title: Adding items to Swift array across multiple threads causing issues (because arrays aren't thread safe) - how do I get around that?
body: <p>I want to add given blocks to an array, and then run all the blocks contained in the array, when requested. I have code similar to this:</p>
  
  <pre><code>class MyArrayBlockClass {
      private var blocksArray: Array&lt;() -&gt; Void&gt; = Array()
  
      private let blocksQueue: NSOperationQueue()
  
      func addBlockToArray(block: () -&gt; Void) {
          self.blocksArray.append(block)
      }
  
      func runBlocksInArray() {
          for block in self.blocksArray {
              let operation = NSBlockOperation(block: block)
              self.blocksQueue.addOperation(operation)
          }
  
          self.blocksQueue.removeAll(keepCapacity: false)
      }
  }
  </code></pre>
  
  <p>The problem comes with the fact that addBlockToArray can be called across multiple threads. What's happening is addBlockToArray is being called in quick succession across different threads, and is only appending one of the items, and so the other item is therefore not getting called during runBlocksInArray.</p>
  
  <p>I've tried something like this, which doesn't seem to be working:</p>
  
  <pre><code>private let blocksDispatchQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
  
  func addBlockToArray(block: () -&gt; Void) {
      dispatch_async(blocksDispatchQueue) {
          self.blocksArray.append(block)
      }
  }
  </code></pre>