The goal of program synchronization is to ensure data consistency and integrity for all processes. It is essential that these running processes do not interrupt each other to avoid the risk of deadlocks and other synchronization problems.

In synchronization, there are two types of processes:

**Independent process -**The execution does not affect other processes executing.

Coordinated process - Can affect or be affected by other processes executing.

Problems arise in coordinated process also because the resources are shared.

Critical Section Problem

The critical section is a code segment that needs synchronization to maintain data consistency over shared variables. The problem needs a solution for coordinated processes to access shared resources without creating inconsistencies.

The solution must satisfy these three conditions:

  1. Mutual exclusion: No other processes must execute the critical section if there is already a process executing it.
  2. Progress: If no process is in the critical section, and other processes are waiting for their turn, only those processes that finished their critical section may decide which will enter the critical section next.
  3. Bounded waiting: A bound must exist on the number of times that other processes are allowed to enter their critical sections after a process has made a request to enter its critical section and before that request is granted.

Semaphores

A semaphore is a signaling mechanism to tell processes or threads whether to wait for signal execution. Semaphores is a solution to the critical section problem.

The main difference between mutex and semaphores is that finished processes themselves can signal semaphores, allowing them to decide who enters next. Mutex can only be signaled by the thread called a wait function, strictly tying the processes in a ****lock.

There are two types of semaphores:

Binary semaphore - They can only be either 0 or 1. They are also known as mutex locks, as the locks can provide mutual exclusion.

Counting semaphore - They can have any value and are not restricted to a certain domain. They can be used to control access to a resource that has a limitation on the number of simultaneous accesses.