dispatch_once(3)

✨ dispatch_once(3) β€” Library Functions Manual ✨

okay bestie, gather round, because today we're talking about the absolute icon of "do it ONCE and never again" β€” dispatch_once. it lives in the library functions manual, it's giving main character energy, and fr fr it's the cleanest way to make sure your setup code runs exactly one time and not a single time more. πŸŽ€


🌸 NAME 🌸

dispatch_once β€” execute a block only once πŸ’…


πŸ¦‹ SYNOPSIS πŸ¦‹

#include <dispatch/dispatch.h>

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

void
dispatch_once_f(dispatch_once_t *predicate, void *context,
    void (*function)(void *));

like, look at that signature. predicate is your little "have we done this yet??" flag, and block is the thing you wanna run exactly once. no notes. 🫢


πŸ’– DESCRIPTION πŸ’–

The dispatch_once() function provides a simple and efficient mechanism to run an initializer exactly once, similar to pthread_once(3). one time. ONE. that's the whole vibe. ✨

and the way that well designed code hides the use of lazy initialization?? obsessed. you don't make the caller think about it, you just quietly handle it inside. here's the moment:

FILE *getlogfile(void)
{
        static dispatch_once_t pred;
        static FILE *logfile;

        dispatch_once(&pred, ^{
                logfile = fopen(MY_LOG_FILE, "a");
        });

        return logfile;
}

see how the static dispatch_once_t pred; and the static FILE *logfile; just sit there being all lowkey?? then dispatch_once(&pred, ^{ ... }) fires the fopen(MY_LOG_FILE, "a") exactly once, and every other call just skips straight to return logfile;. it's giving "I already handled that, bestie." 😌πŸ”₯


πŸ‘‘ FUNDAMENTALS πŸ‘‘

The dispatch_once() function is a wrapper around dispatch_once_f(). that's it, that's the tea. dispatch_once is the cute block-based one, and it's just wrapping the function-pointer-based dispatch_once_f. iykyk. πŸ’œ


🌈 SEE ALSO 🌈


⚠️ quick vibe check: use a properly initialized dispatch_once_t *predicate (like that static dispatch_once_t pred;) β€” don't be out here inventing your own one-shot logic when this exists. it's literally built for this. 🧚

and that's the page, bestie!! this gem comes from the Darwin crew, dated May 1, 2009 β€” a true vintage queen that still slays today. πŸ“πŸ’– no cap.