Вы находитесь на странице: 1из 15

Title:- Semaphore

Term paper:-operating system

Submitted to:- Submitted by:-


Sameep kaur Sewa Singh

Sewasingh.vadan2@gmail.com

Jalandhar-Delhi G.T. Road (NH-1), Phagwara, Punjab (INDIA) - 144402. TEL:


+91-1824-404404 Toll Free: 1800 102 4431 info@lpu.co.in
Acknowledgement

I would like to thank many peoples, but will only name a few here. First of all I
would like to thanks our Teacher sameep kaur for their consultation, without which
I would not have come to know about such wonderful field.

Then I would like to thanks all the people in Technologies department, from
faculty members of the office peoples. And with them I would also like to thanks
the Lovely Professional University for providing with this kind of unique training
were the student are given to work on real time projects.

All this is only possible due to my parent. So I am grateful to them for providing
me with whenever and whatever was needed and for their moral support.
INDEX

CONTENTS page no.


1. Introduction of Semaphore 1
2. Definition of Semaphore 2
3. Semaphore Types 3
4. Basic Properties of Semaphores 3
5. Implementation 4

6. Semaphores Without Busy Waiting 6


7. General semaphore and Binary semaphore 7
8.Creating and Accessing Semaphore Sets 8
9. Usage of Semaphore 9
10.Disadvantage & Problems 10
11.Conclusion 11
12.Reference 12
1. Introduction of Semaphore
semaphores are a technique for coordinating or synchronizing activities in which
multiple processes compete for the same operating system resources. A semaphore
is a value in a designated place in operating system (or kernel) storage that each
process can check and then change. Depending on the value that is found, the
process can use the resource or will find that it is already in use and must wait for
some period before trying again. Semaphores can be binary (0 or 1) or can have
additional values. Typically, a process using semaphores checks the value and
then, if it using the resource, changes the value to reflect this so that subsequent
semaphore users will know to wait.
Semaphores are commonly use for two purposes: to share a common memory
space and to share access to files. Semaphores are one of the techniques for
interprocess communication (IPC). The C programming language provides a set of
interfaces or "functions" for managing semaphores

A signal is a mechanical or electrical device erected beside a railway line to pass


information relating to the state of the line ahead to train drivers/engineers. The
driver interprets the signal's indication and acts accordingly. Typically, a signal
might inform the driver of the speed at which the train may safely proceed, or it
may instruct the driver to stop.it is use in railway signal .

Page no.1
2. Definition of Semaphore
A hardware or software flag used to indicate the status of some activity. A shared space for
interprocess communications controlled by "wake up" and "sleep" commands. A semaphore is a
protected variable or abstract data type that constitutes a classic method of controlling access by
several processes to a common resource in a parallel programming environment.

Semaphores are devices used to help with synchronization. If multiple processes share a common
resource, they need a way to be able to use that resource without disrupting each other. You want
each process to be able to read from and write to that resource uninterrupted.

A semaphore will either allow or disallow access to the resource, depending on how it is set up.
One example setup would be a semaphore which allowed any number of processes to read from
the resource, but only one could ever be in the process of writing to that resource at a time.

• Non-negative integer with atomic increment and decrement

• Integer ‘S’ that (besides init) can only be modified by:

– P(S) or S.wait(): decrement or block if already 0

-- V(S) or S.signal(): increment and wake up process if any

Page no.2
3. Semaphore Types
• Counting Semaphores (integer value can range over an unrestricted domain.)

– Any integer

– Used for synchronization

• Binary Semaphores (integer value can range only between 0


and 1; can be simpler to implement.)

– Value is limited to 0 or 1

Used for mutual exclusion

A binary semaphore is limited to the values 0 and 1.


– A V operation applied to a semaphore whose value is already 1 has no effect.
– Binary semaphores are also called “mutex locks”.
– With some implementations of binary semaphores, sometimes P is named “lock”
and
V is named “unlock”.

4..Basic Properties of Semaphores


Semaphores have the following properties.
� A semaphore takes only integer values. We, however, would limit to
semaphores that take only binary values. In general, we may even have a data-
structure in which every entry is a semaphore. Usually, such structures are required
for establishing a set of processes that need to communicate. These are also
required when a complex data structure like a record is shared.

� There are only two operations possible on a semaphore.


• A wait operation on a semaphore decreases its value by one.
wait(s): while s < 0 do noop; s := s - 1;
• A signal operation increments its value, i.e. signal(s): s : = s + 1;
• A semaphore operation is atomic and indivisible. This essentially ensures
both wait and signal operations are carried out without interruption. This

Page no.3
may be done using some hardware support and can be explained as follows. The
interrupt signal is recognized by the processor only after these steps have been
carried out. Essentially, this means it is possible to use disable and enable signals
to enforce indivisibility of operations. The wait and signal operations are carried
out indivisibly in this sense.

5.Implementation
Counting semaphores are equipped with two operations, historically denoted as V and P (see
below). Operation V increments the semaphore S, and operation P decrements it. The semantics
of these operations is shown below. Square brackets are used to indicate atomic operations, i.e.
operations which appear indivisible from the perspective of other processes.

function V(semaphore S):


Atomically increment S
[S ← S + 1]

function P(semaphore S):


repeat:
Between repetitions of the loop other processes may operate on the semaphore
[if S > 0:
Atomically decrement S - note that S cannot become negative
S←S-1
break]

The value of the semaphore S is the number of units of the resource that are currently available.
The P operation wastes time or sleeps until a resource protected by the semaphore becomes
available, at which time the resource is immediately claimed. The V operation is the inverse: it
makes a resource available again after the process has finished using it.

Many operating systems provide efficient semaphore primitives which mean that one waiting
processes is awoken when the semaphore is free. This means that processes do not waste time
checking the semaphore value and context switching unnecessarily.

The counting semaphore concept can be extended with the ability to claim or return more than
one "unit" from the semaphore. a technique implemented in UNIX. The
modified V and Poperations are as follows:
Page no.4
function V(semaphore S, integer I):
[S ← S + I]

function P(semaphore S, integer I):


repeat:
[if S >= I:
S←S-I
break]

To avoid starvation, a semaphore may have an associated queue of processes (usually a first-in,
first out). If a process performs a P operation on a semaphore that has the value zero, the process
is added to the semaphore's queue. When another process increments the semaphore by
performing a V operation, and there are processes on the queue, one of them is removed from the
queue and resumes execution. When processes have different priorities the queue may be ordered
by priority, so that the highest priority process is taken from the queue first.

If the implementation does not ensure atomicity of the increment, decrement and comparison
operations, then there is a risk of increments or decrements being forgotten, or of the semaphore
value becoming negative. Atomicity may be achieved by using a machine instruction that is able
to read, modify and write the semaphore in a single operation. In the absence of such a hardware
instruction, an atomic operation may be synthesized through the use of a software mutual
exclusion algorithm. On uniprocessor systems, atomic operations can be ensured by temporarily
suspending preemption or disabling hardware interrupts. This approach does not work on
multiprocessor systems where it is possible for two programs sharing a semaphore to run on
different processors at the same time.

Implement Semaphores
class Semaphore
{
private int value;
public Semaphore()
{value = 0;}
public Semaphore (int initial)
{
value = initial;}
public void P(()
Page no.5
{
wantToEnterCS();
// Use any viable busy-waiting mutex solution
while (value == 0)
{
finishedInCS();
wantToEnterCS();
}
value --;
finishedInCS();

Two processes can execute P () and V () on the same semaphore at the same time

1.No process may be interrupted in the middle of these operations

2.Thus, implementation becomes the critical section problem where the P and V code are
placed in the critical section.

3.Could now have busy waiting in critical section implementation

• But implementation code is short


• Little busy waiting if critical section rarely occupied

6. Semaphores Without Busy Waiting


struct Semaphore {
int value;
struct process *list; // list of waiting processes
}

wait(Semaphore s){
s.value--;
if (s.value < 0) {
add this process to s.list;
block(); // block this process
}
}

Page no.6
signal(Semaphore s){
s.value++;
if (s.value <= 0) {
remove a process P from s.list;
wakeup(P);
}

7. General semaphore and Binary semaphore

General semaphore also called counting semaphore.it is a varible n whose value equal to no. of
items in the buffer. where as binary is more restricted version having 0 and 1 value.Binary
semaphore are easier to implement. if there are several processes are waiting for critical
section...general semaphore value is extended to more negative...but in case of binary
semaphore ,semphore value only between 0 and 1.

Binary semaphores are implemented as a set of macros that use the existing counting semaphores
primitives. The difference between counting and binary semaphores is that the counter of binary
semaphores is not allowed to grow above the value 1. Repeated signal operation are ignored. A
binary semaphore can thus have only two defined states:

• Taken, when its counter has a value of zero or lower than zero. A negative number
represent the number of threads queued on the binary semaphore.
• Not taken, when its counter has a value of one.

Page no.7
Binary semaphores are different from mutexes because there is no the concept of ownership, a
binary semaphore can be taken by a thread and signaled by another thread or an interrupt
handler, mutexes can only be taken and released by the same thread. Another difference is that
binary semaphores, unlike mutexes, do not implement the priority inheritance protocol.

8. 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

Page no.8
9. Usage of Semaphore

Suppose we have two processes P1 and P2 that need mutual exclusion. We shall use a
shared semaphore variable use with an initial value = 0. This variable is accessible from
both P1 and P2. We may require that both these processes have a program structure that
uses repeat – until pair as a perpetual loop. The program shall have the structure as shown
below:
repeat
Some process code here
wait (use);
enter the critical section (the process manipulates a shared area);
signal (use);
the rest of the process code.
until false;

With the repeat{until sequence as defined above, we have an infinite loop for both the processes.
On tracing the operations for P1 and P2 we notice that only one of these processes can be in its
critical section. The following is a representative operational sequence. Initially, neither process
is in critical section and, therefore, use is 0.

� Process P1 arrives at the critical section first and calls wait (use).
� It succeeds and enters the critical section setting use = - 1.
� Process P2 wants to enter its critical section. Calls wait procedure.
� As use < 0. P2 does a busy wait.
� Process P1 executes signal and exits its critical section. use = 0 now.
� Process P2 exits busy wait loop. It enters its critical section use = -1.

The above sequence continues.


Yet another good use of a semaphore is in synchronization amongst processes. A process
typically may have a synchronizing event. Typically one process generates an event and
the other process awaits the occurrence of that event to proceed further. Suppose we have
our two processes, Pi and Pj . Pj can execute some statement sj only after a statement si in
process Pi has been executed. This synchronization can be achieved with a semaphore se
initialized to -1 as follows:
� In Pi execute the sequence si; signal (se);
� In Pj execute wait (se); sj ;
Now process Pj must wait completion of si before it can execute sj . With this example, we have
demonstrated use of semaphores for inter-process communication. We shall next discuss a few
operational scenarios where we can use semaphores gainfully.

Page no.9
10.Disadvantage & Problems

What Problems can Arise When Semaphores are Used

• Deadlock – two or more processes are waiting indefinitely for an event that can be caused
by only one of the waiting processes.

• Starvation – indefinite blocking. A process may never be removed from the semaphore
queue in which it is suspended.

Disadvantage
The main disadvantage of the semaphore is that it requires busy waiting, which wastes
CPU cycle that some other process might be able to use productively

• This type of semaphore is also called a spinlock because the process “spins” while
waiting for the lock.

• To overcome the busy waiting problem, we create two more operations:

• block–place the process invoking the operation on the appropriate waiting queue.

• wakeup –remove one of processes in the waiting queue and place it in the ready queue.

Page no.10
11.Conclusion
Semaphores are commonly use for two purposes: to share a common
memory space and to share access to files. Semaphores are one of the
techniques for interprocess communication (IPC). The C programming
language provides a set of interfaces or "functions" for managing
semaphores.
General semaphore also called counting semaphore.it is a varible n
whose value equal to no. of items in the buffer. where as binary is more
restricted version having 0 and 1 value.Binary semaphore are easier to
implement. if there are several processes are waiting for critical
section...general semaphore value is extended to more negative...but in
case of binary semaphore ,semphore value only between 0 and 1.

Page no.11
12. Reference
[1] http://greenteapress.com/semaphores/downey08semaphores.pdf

[2 http://www.cs.jhu.edu/~yairamir/cs418/os3/sld021.htm

[3 http://nptel.iitm.ac.in/courses/Webcourse-contents/IISc-BANG/Operating
%20Systems/pdf/Lecture_Notes/Mod%206_LN.pdf]

[4] http://www.semaphore-software.com/

[5] http://wiki.answers.com/Q/What_is_semaphore_in_operating_system

Page no.12

Sewasingh.vadan2@gmail.com

Вам также может понравиться