When creating safe read streams in Swift, why is the variable created outside the parallel queue?

public class Account {
    // MARK: Initializer
    // Custom initializer

    // MARK: Stored Properties
    let concurrentQueue: DispatchQueue = DispatchQueue(
        label: "concurrentQueue",
        qos: DispatchQoS.userInitiated,
        attributes: [DispatchQueue.Attributes.concurrent]
    ) 

    private var _name: String

    public name: String {
        get { 
            return self.concurrentQueue.sync { return self._name } 
        }

        set {
            self.concurrentQueue.async(flags: .barrier) {
                self._name = newValue
            }
        }
    }
}

Let's say you have a class as above where you need thread safety.

What is the difference between a getter in a class Accountand a getter definition like this?

get { 
    var result: String!
    self.concurrentQueue.sync { result = self._name } 
    return result
}    

Currently, I am hugging my head over thread safety, and I always see that reads are created as the last. It seems to me that they are almost the same ... am I mistaken?

Source: GCD Tutorial

+1
source share
1 answer

There is no difference. There are two methods DispatchQueue.sync:

public func sync(execute block: () -> Swift.Void)
public func sync<T>(execute work: () throws -> T) rethrows -> T

: , sync.

get { 
    return self.concurrentQueue.sync { return self._name } 
}

sync { ... } self._name, . ( ) ( Void):

get { 
    var result: String!
    self.concurrentQueue.sync { result = self._name } 
    return result
}

, , . return Void:

public func async(..., execute work: @escaping @convention(block) () -> Swift.Void)
+1

Source: https://habr.com/ru/post/1684275/


All Articles