22. Thread Synchronization

In Chapter 21, we discussed the details of multithreaded programming using the Task Parallel Library (TPL) and Parallel LINQ (PLINQ). One topic we specifically avoided, however, was thread synchronization, which prevents race conditions while avoiding deadlocks. Thread synchronization is the topic of this chapter.

A mind map depicts the various concepts discussed in thread synchronization. They are, (1) the need for thread synchronization, (2) monitor, (3) lock, (4) volatile, (5) System.Threading.Interlocked, (6) System.Threading.Mutex, (7) resent events, and (8) thread-local storage.

We begin with a multithreaded example with no thread synchronization around shared data—resulting in a race condition in which data integrity is lost. This discussion serves as the introduction for why we need thread synchronization. It is followed by coverage of myriad mechanisms and best practices for ...

Get Essential C# 8.0, 7th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.