Synchronize Properties in Swift 3 using GCD

后端 未结 2 1794
[愿得一人]
[愿得一人] 2021-02-07 12:16

I watched this years WWDC GCD talk lately and I think there is a code snippet something is wrong with. It is about making a property thread-safe using D

2条回答
  •  青春惊慌失措
    2021-02-07 12:33

    I'd like just to show another approach that makes you able to read concurrently, but block everything while writing by using a dispatch barrier.

    class MyObject {
    private var internalState: Int
    private let internalQueue = DispatchQueue(label: "reader-writer", attributes: .concurrent)
    
    var state: Int {
        get {
            return internalQueue.sync { internalState }
        }
    
        set (newState) {
            internalQueue.async(flags: .barrier) { internalState = newState }
        }
      }
    }
    

    With that approach, reads can occur concurrently on the queue, but writes are executed exclusively, due to the barrier.

    This is just a Swift 3 conversion of an approach explained in the book Effective Objective C 2.0, written by Matt Galloway.

提交回复
热议问题