GCD中提供了dispatch_once和@synchrornized两种类型互斥锁,解决线程间的安全问题,个人强烈建议使用dispatch_once,下面用实现单例的代码简单演示两种互斥锁(代码相当简单)
dispatch_once
+ (instancetype)oncetokenPerson
{
static id person;
static dispatch_once_t onceToken;
dispatch_once(&onceToken,^{
[NSThread sleepForTimeInterval:0.5f];
person = [[self alloc] init];
});
return person;
}
@synchronized
//@synchronized
+ (instancetype)synchonizedPserson
{
static id person;
@synchronized (self){
if (person == nil) {
[NSThread sleepForTimeInterval:0.5f];
person = [[self alloc] init];
}
}
return person;
}