objective c - How can I multithread the creation of a lazily loaded property? -


 - (nshashtable *)pollers  {     if (!_pollers) {         dispatch_sync(self.serialqueue, ^{             _pollers = [nshashtable weakobjectshashtable];         });     }      return _pollers;  } 

pollers nonatomic property on singleton. there other methods in singleton objects added pollers, , i'm using @synchronized addition ([self.pollers addobject:____]).

anyway... have question code above. if 2 threads simultaneously call function, both past if (!_pollers) code, , both dispatch _pollers = [nshashtable weakobjectshashtable]; code synchronously on our custom serialqueue. we'll run code twice.

is there better way this?

you need single dispatch_once function this

your serial queue redundant, dispatch_once ensure block called once (even if invoked @ same time multiple threads), contrary pds says.

the documentation states that:

if [dispatch_once is] called simultaneously multiple threads, this function waits synchronously until block has completed.

your if statement redundant, as pointed out josh.

therefore want:

- (nshashtable *)pollers  {     static dispatch_once_t t;     dispatch_once(&t, ^{         _pollers = [nshashtable weakobjectshashtable];     });      return _pollers; } 

it's worth noting you'll need thread safe implementation of singleton's sharedinstance in order bulletproof. can in same way dispatch_once. example:

static singleton* sharedinstance;  +(instancetype) sharedinstance {     static dispatch_once_t t;     dispatch_once(&t, ^{         sharedinstance = [[self alloc] init];     });      return sharedinstance; } 

Comments

Popular posts from this blog

authentication - Mongodb revoke acccess to connect test database -

r - Update two sets of radiobuttons reactively - shiny -

ios - Realm over CoreData should I use NSFetchedResultController or a Dictionary? -