Introduction
As we saw in Chapter 1, Threading Basics, it is problematic to use a shared object simultaneously from several threads. However, it is very important to synchronize those threads so that they perform operations on that shared object in a proper sequence. In the Locking with a C# lock keyword recipe, we faced a problem called the race condition. The problem occurred because the execution of those multiple threads was not synchronized properly. When one thread performs increment and decrement operations, the other threads must wait for their turn. Organizing threads in such a way is often referred to as thread synchronization.
There are several ways to achieve thread synchronization. First, if there is no shared object, there is no need for synchronization at all. Surprisingly, it is very often the case that we can get rid of complex synchronization constructs by just redesigning our program and removing a shared state. If possible, just avoid using a single object from several...