Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k 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 Reply

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

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...