Safe Global Initialization

Sometimes you need to perform one-time initialization and have the work performed exactly one time, no matter how many threads are wanting that initialization to happen. This is often used for lazy initialization or for creating the One True Object when using singletons. There is a technique called Double-Checked Locking to do this, but it is very hard to get right. You can use pthread_once() to serialize a one-time initialization. You can also use dispatch_once().

void dispatch_once (dispatch_once_t *predicate, void (^block)(void));

s​t​a​t​i​c​ ​d​i​s​p​a​t​c​h​_​o​n​c​e​_​t​ ​i​n​i​t​i​a​l​i​z​a​t​i​o​n​P​r​e​d​i​c​a​t​e​;​ s​t​a​t​i​c​ ​b​l​a​h​ ​*​s​t​u​f​f​T​o​I​n​i​t​i​a​l​i​z​e​ d​i​s​p​a​t​c​h​_​o​n​c​e​ ​(​&​i​n​i​t​i​a​l​i​z​a​t​i​o​n​P​r​e​d​i​c​a​t​e​,​ ...

Get Advanced Mac OS X Programming: The Big Nerd Ranch Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.