GCD with static functions of a struct

前端 未结 2 1137
醉酒成梦
醉酒成梦 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:54

    Use a semaphore, dispatch_sync isn't appropriate because you need a synchronous return value from getInstance:

    class SingleSome {
    
        struct Static {
            private static var instance: SingleSome?
            private static let lock = dispatch_semaphore_create(1)
    
            //need barrier sync
            static func getInstance(block: () -> SingleSome) -> SingleSome {
                dispatch_semaphore_wait(lock, DISPATCH_TIME_FOREVER)
                var value = instance
                if value == nil {
                    instance = block()
                    value = instance
                }
                dispatch_semaphore_signal(lock)
                return value!
            }
    
            static func remove() { //need barrier sync
                dispatch_semaphore_wait(lock, DISPATCH_TIME_FOREVER)
                instance = nil
                dispatch_semaphore_signal(lock)
            }
        }
    
    }
    

    Also note that as written this is subject to deadlocks if block results in either remove or getInstance being called as dispatch_semaphore_t is not thread recursive.

提交回复
热议问题