Shared Mutable State

Shared Mutable State

How can we deal with the complexities and troubles brought by shared mutable state in our code? Presented at AltConf 2018.

06609d73ad2165c4aafcf65a1ddb9563?s=128

Greg Heo

June 06, 2018
Tweet

Transcript

  1. @gregheo AltConf, June 2018 Shared Mutable State !

  2. @gregheo AltConf, June 2018 State

  3. @gregheo AltConf, June 2018 Exclusive Shared Immutable Mutable

  4. @gregheo AltConf, June 2018 Make it difficult
 to get wrong

  5. @gregheo AltConf, June 2018 "

  6. @gregheo AltConf, June 2018 queue1.async {
 
 } queue2.async {


    
 
 } 
 stuff()
 
 things()
 things2()

  7. @gregheo AltConf, June 2018 Exclusive Shared Immutable Mutable private let

    private var
 private queue UIDevice
 Screen size &
  8. @gregheo AltConf, June 2018 Fewer entry points

  9. @gregheo AltConf, June 2018 internal
 private
 fileprivate

  10. @gregheo AltConf, June 2018 Pass in values

  11. @gregheo AltConf, June 2018 class Printer { var num: Int

    func print() { print(num) } }
  12. @gregheo AltConf, June 2018 func printNum(num: Int) { print(num) }

  13. @gregheo AltConf, June 2018 Who enqueues
 the queues?

  14. @gregheo AltConf, June 2018 
 // call from anywhere!
 public

    func something() {
 privateQueue.sync { … } }

  15. @gregheo AltConf, June 2018 Queue Callback

  16. @gregheo AltConf, June 2018 
 // always call on the

    main queue!
 public func something() 

  17. @gregheo AltConf, June 2018 
 // always call on the

    main queue!
 public func something() {
 dispatchPrecondition(condition: .onQueue(.main))
 }

  18. @gregheo AltConf, June 2018 # Do I have order right?

    Is the order even knowable? Is it concurrent?
  19. @gregheo AltConf, June 2018 $ Too much access Mutable variables

    Thread uncertainty
  20. @gregheo AltConf, June 2018 ✅ “Limit access “Functional” approach “Private

    queues
  21. @gregheo AltConf, June 2018 # $ ✅

  22. @gregheo AltConf, June 2018 Make it difficult
 to get wrong