25-08-2017, 09:32 PM
Semaphores
![Microsoft PowerPoint Document .ppt](https://seminarproject.net/images/attachtypes/ppt.gif)
Race condition
To avoid race conditions there should be a mutual exclusion which is a way for making sure if one process is using the shared variable/file, the other processes will be excluded from doing the same thing.
That part of each program where the shared memory is accessed is called the critical region or critical section.
To not have race conditions, processes shouldn’t be in their critical regions in the same time.
Semaphore Definition
A semaphore is a data structure that is shared by several processes. Semaphores are most often used to synchronize operations (to avoid race conditions) when multiple processes access a common, non-shareable resource.
By using semaphores, we attempt to avoid other multi-programming problems such as:
Starvation
Occurs when a process is habitually denied access to a resource it needs.
Deadlock
Occurs when two or more processes each hold a resource that the other needs while waiting for the other process to release its resource.
To indicate a process has gained access to the resource, the process decrements the semaphore.
For events to progress correctly, the test and decrement operation on the semaphore must be
atomic (i.e., noninterruptible/indivisible).
There are two kinds of Semaphores:
Binary semaphores
Control access to a single resource, taking the value of 0 (resource is in use) or 1 (resource is available).
Counting semaphores
Control access to multiple resources, thus assuming a range of nonnegative values.
Creating and Accessing Semaphore Sets
Before a semaphore set can be used, it must be created.
The creation of the semaphore set generates a unique data structure that the system uses to identify and manipulate the semaphores.
A conceptual arrangement of a system semaphore structure for a newly allocated set of three semaphores is shown in Figure
Semaphore Control
The semctl system call allows the user to perform a variety of generalized control operations on the system semaphore structure, on the semaphores as a set, and on individual semaphores.
Semaphore Control Details
IPC_SET
Modify a restricted number of members in the semid_ds structure. The members sem_perm.uid, sem_perm.gid and sem_perm.mode can be changed if the effective ID of the accessing process is that of the superuser or is the same as the ID value stored in sem_perm.cuid or sem_perm.uid. To make these changes, a structure of the type semid_ds must be allocated. The appropriate members' values are then assigned, and a reference to the modified structure is passed as the fourth argument to the semctl system call.
IPC_RMID
Remove the semaphore set associated with the semaphore identifier.