O'Reilly logo

Advanced Mac OS X Programming: The Big Nerd Ranch Guide by Mark Dalrymple

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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​,​ ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required