45、使用dispatch_once来执行只需要运行一次的线程安全代码

+ (id)sharedInstance {
  static EOCClass *sharedInstance = nil;
  static dispatch_once_t onceToken; // 只初始化一次
  dispatch_once(&onceToken, ^{
    sharedInstance = [[self alloc] init];
  });
  return sharedInstance;
}

dispatch_once更高效,没有使用重量级的同步机制。

要点:

  • 经常需要编写“只需执行一次的线程安全代码”(thread-safe single-code execution)。通过GCD所提供的dispatch_once函数,很容易就能实现此功能

  • 标记应该声明在staticglobal作用域中,这样的话,在把只需执行一次的块传给dispatch_once函数时,传进去的标记也是相同的

Last updated

Was this helpful?