单例创建 dispatch_once  @synchronized

1、@synchronized

static InstanceClass *instance;

+ (InstanceClass *)defaultInstance{
   @synchronized (self){
     if (instance == nil) {
        instance = [[InstanceClass alloc] init];
     }
    }

   return instance;
}

2、GCD

static InstanceClass *instance;

+ (InstanceClass *)defaultInstance{
   static dispatch_once_t onceToken;
   dispatch_once
(&onceToken, ^{
     instance
= [[InstanceClass alloc] init];
   });
   return
instance;
}

两种方式都能起到线程安全的作用,尤其是在多cpu的环境下
原文地址:https://www.cnblogs.com/cnsec/p/11515818.html