Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

swift - GCD with static functions of a struct

how'd you apply thread safe functionality to 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
        }
    }

}

reason a block was used as param as there could be inherited objects of SingleSome

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...