首页 > 其他 > 详细

使用dispatch_once实现单例

时间:2017-02-11 15:47:54      阅读:222      评论:0      收藏:0      [点我收藏+]

转自http://www.jianshu.com/p/e03aa66a197f

很多人实现单例会这样写: 

@implementation XXClass

+ (id)sharedInstance {
    static XXClass *sharedInstance = nil;
    @synchronized(self) {
        if (!sharedInstance) {
            sharedInstance = [[self alloc] init];
        }
    }
    return sharedInstance;
}

相比之下: 

@implementation XXClass

+ (id)sharedInstance {
    static XXClass *sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if (!sharedInstance) {
            sharedInstance = [[self alloc] init];
        }
    });
    return sharedInstance;
}

使用dispatch_once可以简化代码并且彻底保证线程安全,开发者无需担心加锁或同步。此外,dispatch_once更高效,它没有使用重量级的同步机制,若是那样做的话,每次运行代码前都要获取锁。相反,此函数采用“原子访问”来查询标记,以判断其所对应的代码原来是否已经执行过。在64位Mac OS X上测试,后者的执行速度要比前者快一倍。

 

使用dispatch_once实现单例

原文:http://www.cnblogs.com/liuting-1204/p/6389205.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!