Synchronization techniques among threads

When you create code that is threadsafe but still benefits from sharing data or resources between threads, the most important aspect of programming becomes the ability to synchronize threads.

Synchronization is the cooperative act of two or more threads that ensures that each thread reaches a known point of operation in relationship to other threads before continuing. Attempting to share resources without correctly using synchronization is the most common cause of damage to application data.

Typically, synchronizing two threads involves the use of one or more synchronization primitives. Synchronization primitives are low-level functions or application objects (not IBM® i objects) that your application uses or creates to provide the synchronization behavior that the application requires.

Here are the most common synchronization primitives in order of least to most computationally expensive:
  • Compare and swap
  • Mutual exclusion (mutexes) and threads
  • Semaphores and threads
  • Condition variables and threads
  • Threads as synchronization primitives
  • Space location locks
  • Object locks

These concepts pertain to all programming languages. To determine how each language enables these concepts, refer to the Language topic in the information center for the specific language.