liveBook · Manning

Synchronization

As explained in C# Concurrency: Asynchronous and multithreaded programming

Synchronization is the coordination of concurrent operations so that they occur in a controlled sequential order rather than simultaneously.

Synchronization coordinates concurrent operations so shared work occurs in a controlled sequential order. Locks prevent partial updates, but excessive locking can erase the performance benefit of multiple threads. section 7.5 section 7.0

Apply synchronization with these safeguards:

  • Protect shared-data access with a lock and keep the protected region as short as practical. section 7.5
  • Hold a lock long enough to preserve the entire required operation; if the boundary is uncertain, prefer correctness over parallelism. section 7.7
  • Acquire multiple locks in one consistent order, avoid uncontrolled calls while locked, and remember that thread-safe operations do not automatically compose safely. section 7.7
Listing 7. 13 Multithreaded counting to 10 million
public void GetCorrectValue() 
{
  int theValue = 0;
  object theLock = new Object();

  var threads = new Thread[2];
  for(int i=0;i<2;++i)
  {
     threads[i] = new Thread(()=>
     {
        for(int j=0;j<5000000;++j)
        {
           lock(theLock)
           {
              ++theValue;
           }
        }
     });
     threads[i].Start();
  }

  foreach(var current in threads) 
  { 
     current.Join();
  }
  Console.WriteLine(theValue);
}

A runnable C# example starts two threads, protects each increment with lock, joins both threads, and prints the correct total. section 7.5

Counting to ten million

Two threads each increment a shared value five million times. The lock prevents lost updates, but one thread waits during each increment, potentially making the synchronized version slower than a single-threaded counter. section 7.5

How C# Concurrency: Asynchronous and multithreaded programming covers it

How deep it goes
Explains locks, protected regions, waiting, overhead, lock hierarchy, and practical duration trade-offs.
Examples
Uses a C# counter with two threads, five-million increments each, lock protection, thread joining, and a performance diagram.
What it assumes
Assumes basic threading knowledge and introduces synchronization through shared-data hazards and locked C# code.
What you can do after
Diagnose/debug lost updates and synchronization overhead, then choose safer lock boundaries for shared data.
How it connects
Relates to multithreading, locks, partial updates, race conditions, deadlocks, starvation, and thread safety.

Also explained in

Compare how 10 books explain synchronization →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of C# Concurrency: Asynchronous and multithreaded programming. The section links point to the parts of the book it draws on.