Thread safe instantiation of a singleton

前端 未结 5 2087
栀梦
栀梦 2020-12-04 08:28

Which one synchronization method to use to ensure a singleton remains a singleton?

+(Foo*)sharedInstance
{
   @synchronized(self)
   {
      if (nil == _shar         


        
5条回答
  •  爱一瞬间的悲伤
    2020-12-04 08:45

    The fastest thread safe way to do this is with Grand Central Dispatch ( libdispatch ) and dispatch_once()

    +(MyClass *)sharedInstance
    {   
        static MyClass *sharedInstance = nil;
        static dispatch_once_t pred;
    
        dispatch_once(&pred, ^{
            sharedInstance = [[MyClass alloc] init];
        });
    
        return sharedInstance;
    }
    

提交回复
热议问题