liveBook · Manning

Shared resource

As explained in Modern C, Third Edition

A shared object is an object whose storage and value can be accessed by more than one thread.

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.

How Modern C, Third Edition covers it

How deep it goes
Explains initialization ordering, one-time initialization, cleanup, and protection choices, but does not develop memory-model internals.
Examples
Demonstrates a shared error log initialized with call_once and finalized through atexit or at_quick_exit handlers.
What it assumes
Assumes familiarity with threads and C storage duration while distinguishing local, thread-specific, atomic, and mutex-protected data.
What you can do after
Operate shared C objects safely by ordering initialization, guarding one-time setup, protecting critical sections, and arranging cleanup.
How it connects
Connects shared resources with call_once, once_flag, _Atomic, mutexes, condition variables, thread-local storage, and cleanup handlers.

Also explained in

Compare how 3 books explain shared resource →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Modern C, Third Edition. The section links point to the parts of the book it draws on.