In a multithreaded application, there are multiple threads running concurrently. If more than one thread tries to access the same piece of code simultaneously, usually referred to as the critical section, this can lead to unexpected or erroneous behavior. This is where the need for thread synchronization arises; it’s a mechanism to ensure that only one thread executes the critical section at any given time.
Two mechanisms you can utilize to achieve thread synchronization are semaphores or mutexes. They have some differing properties, but in essence they are both variables that are changed before and after the critical section by a thread to make sure that no other threads can execute the segment before that thread has completed it. The main differences are that semaphores have a maximum value that is set at initialization, while mutexes have ownership property, i.e only the thread incrementing its value can decrement it, until zero when it is relinquished.
In the following sections, we will discuss in more detail about both semaphores and mutexes, including a list of properties and a visualization. There are also two exercises to be completed, practicing how to use semaphores and mutexes as thread synchronization mechanisms.