Singleton
A singleton is a type with one instance for the whole process. In C that is a file-scope static object plus a function that returns its address after initializing it once.
Detailed Explanation
static struct Config cfg;
static int ready;
struct Config *config_get(void)
{
if (!ready) {
config_init(&cfg);
ready = 1;
}
return &cfg;
}
That is the pattern. There is no private constructor to enforce it. Anyone who can see struct Config can declare another. Opacity plus a single config_get is the enforcement you get.
The lazy if (!ready) is a race if two threads call config_get at once. You need pthread_once, a C11 call_once, or init in main before any thread starts. ready as a plain int is a data race.
Singletons are globals with an API. They make tests order-dependent and they hide coupling. A function that calls config_get internally cannot be given a fake config without link-time games. Prefer passing struct Config * into the functions that need it. Use a process-wide instance only for things that truly are unique: the libc heap, a process-wide trace file you already decided to have.
atexit can register a cleanup for the singleton. Threads must be done using it before that runs. main returning will destroy the process anyway.
A function-local static is a singleton of that function's state (strtok). It is worse: the name is hidden and the function is not reentrant. Prefer a parameter.
Code Examples
#include <stdio.h>
#include <pthread.h>
static pthread_once_t once = PTHREAD_ONCE_INIT;
static int value;
static void init(void)
{
value = 42;
}
static int *answer(void)
{
pthread_once(&once, init);
return &value;
}
int main(void)
{
printf("%d\n", *answer()); /* prints: 42 */
return 0;
}Common Gotchas
Tests that mutate the singleton leak state into the next test
reset it, or do not use a singleton.
A file-scope `static` is already unique to the translation unit
the function is there to control init and to hide the object.
`strtok` is a singleton of parse state
`strtok_r` exists because that was a mistake.
Lazy init without `pthread_once` (or equivalent) is a data race in a multithread
Lazy init without `pthread_once` (or equivalent) is a data race in a multithreaded program