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









