具有结构静态函数的 GCD

GCD with static functions of a struct

您如何将线程安全功能应用于结构的静态函数

class SingleSome {

    struct Static {
        private static var instance: SingleSome?

        //need barrier sync
        static func getInstance(block: () -> SingleSome) -> SingleSome {
            if instance == nil {
                instance = block()
            }
            return instance!
        }

        static func remove() { //need barrier sync
            instance = nil
        }
    }

}

之所以将块用作参数,是因为可能存在 SingleSome

的继承对象

使用信号量,dispatch_sync 不合适,因为您需要来自 getInstance 的同步 return 值:

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)
        }
    }

}

另请注意,如所写,如果块导致 remove 或 getInstance 被调用,则可能会出现死锁,因为 dispatch_semaphore_t 不是线程递归的。

您可以使用私有串行队列来确保在任何时刻只有一个线程可以处于任何临界区。

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
            }
        }
    }

}