liveBook · Manning

Lockless technique

As explained in Modern C, Third Edition

The lock-free property indicates that operations on an atomic type do not require a hidden lock and are indivisible with respect to signal interruption.

A signal can interrupt an operation partway through. An uninterruptible operation appears either not to have started or to have finished when the signal handler runs. A lock-free atomic type provides this property without relying on a hidden lock. section 19.6

TAKEAWAY: Do not use sig_atomic_t as a signal-handler counter. Its loads and stores are uninterruptible, but ++ may split into a load, increment, and store. For counting, use an atomic type only when it has the lock-free property. section 19.6

 #if ATOMIC_LONG_LOCK_FREE > 1
 /**
  ** @brief Keep track of the number of calls into a
  **  signal handler for each possible signal.
  **
  ** Don't use this array directly.
  **
  ** @see sh_count to update this information.
  ** @see SH_PRINT to use that information.
  **/
 extern _Atomic(unsigned long) sh_counts[];
 
 /**
  ** @brief Use this in your signal handler to keep track of the
  ** number of calls to the signal @a sig.
  **
  ** @see sh_counted to use that information.
  **/
 inline
 void sh_count(int sig) {
   if (sig < sh_known) ++sh_counts[sig];
 }
 
 inline
 unsigned long sh_counted(int sig){
   return (sig < sh_known) ? sh_counts[sig] : 0;
 }
 
 #else

The conditional example enables an _Atomic(unsigned long) signal counter only when ATOMIC_LONG_LOCK_FREE > 1; sh_count then increments it in the handler. section 19.6

How Modern C, Third Edition covers it

How deep it goes
Defines uninterruptibility and distinguishes atomic counters from sig_atomic_t, without detailing atomic implementation.
Examples
Uses a conditionally enabled _Atomic(unsigned long) counter incremented by sh_count.
What it assumes
Assumes familiarity with C types and increments while defining uninterruptibility in the signal-handler context.
What you can do after
Apply it via C11 atomic types to select a signal-handler counter when the required lock-free property is available.
How it connects
Connects signal handlers, sig_atomic_t, atomic types, and asynchronous signal safety.

Also explained in

Compare how 3 books explain lockless technique →

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.