Thread safe access to a variable in a class

后端 未结 2 1489
耶瑟儿~
耶瑟儿~ 2021-01-14 08:56

in an application where there could be multiple threads running, and not sure about the possibilities if these methods will be accessed under a multhreaded environment or no

2条回答
  •  借酒劲吻你
    2021-01-14 09:49

    Here is another swift 3 solution which provides thread-safe access to AnyObject.

    It allocates recursive pthread_mutex associated with 'object' if needed.

    class LatencyManager
    {
        private var latencies = [String : TimeInterval]()
    
        func set(hostName: String, latency: TimeInterval) {
            synchronizedBlock(lockedObject: latencies as AnyObject) { [weak self] in
                self?.latencies[hostName] = latency
            }
        }
    
        /// Provides thread-safe access to given object
        private func synchronizedBlock(lockedObject: AnyObject, block: () -> Void) {
            objc_sync_enter(lockedObject)
            block()
            objc_sync_exit(lockedObject)
        }
    }
    

    Then you can call for example set(hostName: "stackoverflow.com", latency: 1)

    UPDATE

    You can simply define a method in a swift file (not in a class):

    /// Provides thread-safe access to given object
    public func synchronizedAccess(to object: AnyObject, _ block: () -> Void)
    {
        objc_sync_enter(object)
        block()
        objc_sync_exit(object)
    }
    

    And use it like this:

    synchronizedAccess(to: myObject) {
        myObject.foo()
     }
    

提交回复
热议问题