GCD with static functions of a struct

前端 未结 2 1139
醉酒成梦
醉酒成梦 2020-12-20 03:33

how\'d you apply thread safe functionality to static functions of a struct

class SingleSome {

    struct Static {
        private static var instance: Singl         


        
2条回答
  •  天命终不由人
    2020-12-20 03:59

    You can use a private serial queue to ensure that only one thread can be in any of the critical sections at any instant.

    class SingleSome {
    
        struct Static {
            private static let queue = dispatch_queue_create("SingleSome.Static.queue", nil)
            private static var instance: SingleSome?
    
            static func getInstance(block: () -> SingleSome) -> SingleSome {
                var myInstance: SingleSome?
                dispatch_sync(queue) {
                    if self.instance == nil {
                        self.instance = block()
                    }
                    myInstance = self.instance
                }
                // This return has to be outside the dispatch_sync block,
                // so there's a race condition if I return instance directly.
                return myInstance!
            }
    
            static func remove() {
                dispatch_sync(queue) {
                    self.instance = nil
                }
            }
        }
    
    }
    

提交回复
热议问题