title: DispatchQueue barrier issue
body: <p>trying to make thread safe array but it works not as I expected</p>
  
  <pre><code>import Foundation
  import PlaygroundSupport
  
  PlaygroundPage.current.needsIndefiniteExecution = true
  
  public class SafeArray&lt;Element&gt; {
      private var array = [Element]()
      private let queue = DispatchQueue(label: "queueBarrier", attributes: .concurrent)
  
      public func append(element: Element) {
          queue.async(flags: .barrier) {
              self.array.append(element)
          }
      }
  
      public var elements: [Element] {
          var result = [Element]()
          queue.sync {
              result = self.array
          }
          return result
      }
  
      public var last: Element? {
          var result: Element?
          queue.sync {
              result = self.array.last
          }
          return result
      }
  }
  
  
  
  
  var safeArray = SafeArray&lt;Int&gt;()
  var array = Array&lt;Int&gt;()
  
  DispatchQueue.concurrentPerform(iterations: 10) { (int) in
      let last = array.last ?? 0
      array.append(last + 1)
      print("array = [..\(last)]")
  }
  
  print(array)
  
  DispatchQueue.concurrentPerform(iterations: 10) { (int) in
      let last = safeArray.last ?? 0
      safeArray.append(element: last + 1)
         print("safeArray = [..\(last)]")
  }
  
  print(safeArray.elements)
  </code></pre>
  
  <p><a href="https://i.stack.imgur.com/UrLJ9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/UrLJ9.png" alt="output of my code"></a></p>
  
  <p>I expected that array should have some mess but safeArray should have numbers from 0 to 9. </p>
  
  <p>I understand that <strong>array</strong> have 3 values but <strong>safeArray</strong> has 10 values as expected. But why this values not from 0 to 9?</p>
  
  <p>Thank you!</p>