A shared resource is an object whose storage and value can be accessed by multiple threads. Establish its state before concurrent access begins, and prevent access after destruction. section 20.2
Prefer these arrangements when several threads need access:
- Initialize static-storage objects before execution, or initialize automatic and allocated objects in their creating thread before sharing them. section 20.2
- Initialize dynamic static-storage data in main before creating threads; otherwise guard initialization with the same once_flag and call_once callback. section 20.2
- Keep data local where possible; use thread_local or tss_create for thread-specific state, _Atomic for small critical data, and mtx_t for critical sections. section 20.8
One-time initialization of a shared log
A shared errlog pointer can be initialized by errlog_fopen, which creates a filename, opens the stream, and enables line buffering. Each thread calls call_once(&errlog_flag, errlog_fopen) immediately before using errlog. The once_flag allows exactly one callback execution and holds other threads until initialization finishes. Register cleanup separately so the stream is not used after errlog_fclose destroys it.


