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 initializeddispatch_once_t *predicate(like thatstatic 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.
π¦ where this page comes from
- alpine 3.24: libdispatch-doc 6.1.2-r0 Β· Apache-2.0
- arch rolling: libdispatch 6.2.2-1 Β· Apache-2.0
- epel 10: libdispatch 1:6.0.2-1.el10_0 Β· Apache-2.0
- epel 9: libdispatch 1:6.0.2-1.el9 Β· Apache-2.0
- fedora 43: libdispatch 1:6.0.2-3.fc43 Β· Apache-2.0
- fedora 44: libdispatch 1:6.0.2-3.fc43 Β· Apache-2.0
- fedora 44: libdispatch 1:6.0.2-4.fc44 Β· Apache-2.0
- nixos 26.05: swift-corelibs-libdispatch 5.10.1
- opensuse-leap 16.0: libdispatch-devel 5.6.3-bp160.1.1 Β· Apache-2.0
- ubuntu jammy: libdispatch-dev 0~svn197-3.3ubuntu2
- Copyright (c) 2008-2009 Apple Inc. All rights reserved
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms