title: How is struct (immutability) related to thread safety
body: <p>I have read <a href="http://chris.eidhof.nl/post/structs-and-mutation-in-swift/" rel="noreferrer">an article about immutability/struct in Swift</a>. There's a part says:</p>
  
  <blockquote>
    <p>In functional programming, side-effects are often considered bad,
    because they might influence your code in unexpected ways. For
    example, if an object is referenced in multiple places, every change
    automatically happens in every place. As we have seen in the
    introduction, when dealing with multi-threaded code, this can easily
    lead to bugs: because the object you are just checking can be modified
    from a different thread, all your assumptions might be invalid.</p>
    
    <p>With Swift structs, mutating does not have the same problems. The
    mutation of the struct is a local side-effect, and only applies to the
    current struct variable. Because every struct variable is unique (or
    in other words: every struct value has exactly one owner), it’s almost
    impossible to introduce bugs this way. <strong>Unless you’re referring to a
    global struct variable across threads, that is.</strong></p>
  </blockquote>
  
  <p>In a bank account example, an account object has to be mutated or replaced at times. Using a <code>struct</code> is not sufficient for protecting an account from problems with updating it from multithreads. <strong>If we use some lock or queue, we can also use a <code>class</code> instance</strong> instead of a <code>struct</code>, right?</p>
  
  <p>I tried writing some code that I'm not sure can result a race condition. The main idea is: two threads both first acquire some information (an instance of <code>Account</code>) then overwrite the variable that hold the information, based on what was acquired.</p>
  
  <pre><code>struct Account {
      var balance = 0
  
      mutating func increase() {
          balance += 1
      }
  }
  
  class ViewController: NSViewController {
  
      override func viewDidLoad() {
          super.viewDidLoad()
  
          // method1()
          method2()
      }
  
      func method1() {
          var a = Account(balance: 3) {
              didSet {
                  print("Account changed")
              }
          }
  
          // https://stackoverflow.com/questions/45912528/is-dispatchqueue-globalqos-userinteractive-async-same-as-dispatchqueue-main
          let queue = DispatchQueue.global()
  
          queue.async {
              a.increase()
              print("global: \(a.balance)")
          }
  
          DispatchQueue.main.async {
              a.increase()
              print("main: \(a.balance)")
          }
      }
  
      func method2() {
          var a = Account(balance: 3) {
              didSet {
                  print("Account changed")
              }
          }
  
          func updateAccount(account : Account) {
              a = account
          }
  
          let queue = DispatchQueue.global()
  
          queue.async { [a] in
              var temp = a
              temp.increase()
              updateAccount(account: temp) // write back
              print("global: \(temp.balance)")
          }
  
          DispatchQueue.main.async { [a] in
              var temp = a
              temp.increase()
              updateAccount(account: temp)
              print("main: \(temp.balance)")
          }
      }
  }
  </code></pre>
  
  <p>If we don't modify the variable <code>a</code> (or, just use <code>let</code> to make it a constant), <strong>what's the benefit of using <code>struct</code> in place of <code>class</code>, in respect of thread-safety, for such a simple structure?</strong> <a href="https://stackoverflow.com/questions/29589007/what-are-the-benefits-of-an-immutable-struct-over-a-mutable-one">There may be other benefits</a>, though. </p>
  
  <p>In real world, the <code>a</code> should be modified in a queue, or be protected by some lock, but <strong>where does the idea of "immutability helps with thread-safety" come from?</strong> </p>
  
  <p>In the example above, is it still possible that both threads get the same value thus producing wrong result?</p>
  
  <p>A quote from <a href="https://softwareengineering.stackexchange.com/questions/171253/does-immutability-entirely-eliminate-the-need-for-locks-in-multi-processor-progr/171298#171298?newreg=d9f4ff5655ac42989808bf970c7d41d6">an answer on StackExchange</a>: </p>
  
  <blockquote>
    <p>Immutability gets you one thing: you can read the immutable object
    freely, without worrying about its state changing underneath you</p>
  </blockquote>
  
  <p>So is the benefit is for read-only?</p>
  
  <p>There's similar questions in Java, e.g. <a href="https://stackoverflow.com/questions/25224033/does-immutability-guarantee-thread-safety">Does immutability guarantee thread safety?</a> and <a href="https://stackoverflow.com/questions/9303532/immutable-objects-are-thread-safe-but-why">Immutable objects are thread safe, but why?</a>.</p>
  
  <p>I also find <a href="https://dzone.com/articles/do-immutability-really-means" rel="noreferrer">a good article</a> in Java on this topic.</p>
  
  <h2>Other resources:</h2>
  
  <ul>
  <li><p><a href="https://rcardin.github.io/programming/thread-safety/immutability/java/scala/2015/09/09/immutability-equal-thread-safety.html" rel="noreferrer">Immutability =
  Thread-safety</a></p></li>
  <li><p><a href="https://softwareengineering.stackexchange.com/questions/171253/does-immutability-entirely-eliminate-the-need-for-locks-in-multi-processor-progr/171298#171298?newreg=d9f4ff5655ac42989808bf970c7d41d6">Does immutability entirely eliminate the need for locks in multi-processor programming?</a></p></li>
  </ul>