0% found this document useful (0 votes)
9 views16 pages

OS-Unit-II(Part-II)

Process synchronization is essential for coordinating the execution of processes to prevent simultaneous access to shared data, which can lead to race conditions. The document discusses various methods for achieving mutual exclusion, including disabling interrupts, lock variables, and strict alternation, each with their own advantages and drawbacks. Additionally, it introduces Peterson's solution as a classic approach to the critical section problem, emphasizing the importance of mutual exclusion, progress, and bounded waiting.

Uploaded by

satyatadi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views16 pages

OS-Unit-II(Part-II)

Process synchronization is essential for coordinating the execution of processes to prevent simultaneous access to shared data, which can lead to race conditions. The document discusses various methods for achieving mutual exclusion, including disabling interrupts, lock variables, and strict alternation, each with their own advantages and drawbacks. Additionally, it introduces Peterson's solution as a classic approach to the critical section problem, emphasizing the importance of mutual exclusion, progress, and bounded waiting.

Uploaded by

satyatadi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

Process Synchronization

Process Synchronization is the task phenomenon of coordinating the execution of processes in such a way that no
two processes can have access to the same shared data and resources.
Process Synchronization is mainly when multiple processes are running together, and more than one processes try
to gain access to the same shared resource or any data at the same time.

Race Conditions
• Several processes access and manipulate the same data concurrently
• The outcome of the execution depends on the particular
order in which the access takes place is called Race Condition
• Prevent race condition by Synchronization
1. Ensure only one process at a time manipulates the critical data

EXAMPLE

Critical Section
1. When more than one processes access a same code segment that segment is known as critical section.
2. Critical section contains shared variables or resources which are needed to be synchronized to maintain
consistency of data variable.
3. In simple terms a critical section is group of instructions/statements or region of code that need to be
executed atomically, such as accessing a resource (file, input or output port, global data, etc.).
1. Each process must request permission to enter its critical section.
2. The section of code implementing this request
is the entry section.
3. The critical section may be followed
by an exit section.
4. The remaining code is the remainder section.

1
UNIT-2 OPERATING SYSTEMS, DEPT.OF CSE, ACOE, SURAMPALEM
A solution to the critical-section problem must satisfy the following three requirements:
1. Mutual exclusion. If process Pi is executing in its critical section, then no other processes
can be executing in their critical sections.
2. Progress. When no process is the critical section, any process that requests entry into
the critical section must be permitted without any delay
3. Bounded waiting. There exists a bound, or limit, 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.

Here process A enters its critical region at time T1. A little later, at
time T2 process B attempts to enter its critical region but fails because
another process is already in its critical region and we allow only one
at a time.
Consequently, B is temporarily suspended until time T3 when A leaves
its critical region, allowing B to enter immediately. Eventually B leaves
(at T 4 ) and we are back to the original situation with no processes in
their critical regions.

Mutual Exclusion with Busy Waiting


Various proposals for achieving mutual exclusion, so that while one process is busy updating shared memory in its
critical region, no other process will enter its critical region and cause trouble.
These are proposals for achieving mutual exclusion:
1. Disabling Interrupts
2. Lock Variables
3. Turn Variable or Strict Alternation Approach

Proposal -1: Disabling Interrupts


1. On a single-processor system, the simplest solution is to have each process disable all interrupts just after entering
its critical region and re-enable them just before leaving it.
2. With interrupts disabled, no clock interrupts can occur.
3. The CPU is only switched from process to process as a result of clock or other interrupts, after all, and with interrupts
turned off the CPU will not be switched to another process.
4. Thus, once a process has disabled interrupts, it can examine and update the shared memory without fear that any
other process will intervene.
Problem of Proposal -1: Disabling Interrupts
1. This approach is generally unattractive because it is unwise to give user processes the power to turn off interrupts.
2. Suppose that one of them did it, and never turned them on again? That could be the end of the system.
3. Furthermore, if the system is a multiprocessor disabling interrupts affects only the CPU that executed the disable
instruction. The other ones will continue running and can access the shared memory.
4. The possibility of achieving mutual exclusion by disabling interrupts—even within the kernel—is becoming less
every day due to the increasing number of multicore chips even in low-end PCs. Two cores are already common, four
are present in high-end machines, and eight or 16 are not far behind.
5. In a multicore (i.e., multiprocessor system) disabling the interrupts of one CPU does not prevent other CPUs from
interfering with operations the first CPU is performing. Consequently, more sophisticated schemes are needed.

Proposal -2: Lock Variables

2
UNIT-2 OPERATING SYSTEMS, DEPT.OF CSE, ACOE, SURAMPALEM
1. As a second attempt, let us look for a software solution.
2. Lock variable is a synchronization mechanism.
3. It uses a lock variable to provide the synchronization among the processes executing concurrently.
4. However, it completely fails to provide the synchronization.
5. Multiprocessor solution
6. Executes in users mode
7. It is implemented as-
8. Initially, lock value is set to 0.
9. Lock value = 0 means the critical section is currently vacant and no process is present inside it.
10. Lock value = 1 means the critical section is currently occupied and a process is present inside it.

Working-

This synchronization mechanism is supposed to work as explained in the following scenes-

Scene-01:
1. Process P0 arrives.
2. It executes the lock!=0 instruction.
3. Since lock value is set to 0, so it returns value 0 to the while loop.
4. The while loop condition breaks.
5. It sets the lock value to 1 and enters the critical section.
6. Now, even if process P0 gets preempted in the middle, no other process can enter the critical section.
7. Any other process can enter only after process P0 completes and sets the lock value to 0.

Scene-02:
1. Another process P1 arrives.
2. It executes the lock!=0 instruction.
3. Since lock value is set to 1, so it returns value 1 to the while loop.
4. The returned value 1 does not break the while loop condition.
5. The process P1 is trapped inside an infinite while loop.
6. The while loop keeps the process P1 busy until the lock value becomes 0 and its condition breaks.
Scene-03:
1. Process P0 comes out of the critical section and sets the lock value to 0.
2. The while loop condition of process P1 breaks.
3. It sets the lock value to 1 and enters the critical section.
4. Now, even if process P1 gets preempted in the middle, no other process can enter the critical section.
5. Any other process can enter only after process P1 completes and sets the lock value to 0.
Failure of the Mechanism-
1. The mechanism completely fails to provide the synchronization among the processes.
2. It can not even guarantee to meet the basic criterion of mutual exclusion.

3
UNIT-2 OPERATING SYSTEMS, DEPT.OF CSE, ACOE, SURAMPALEM
Explanation-
The occurrence of the following scenes may lead to two processes present inside the critical section at the same time-
Scene-01:
Process P0 arrives.
1. It executes the lock!=0 instruction.
2. Since lock value is set to 0, so it returns value 0 to the while loop.
3. The while loop condition breaks.
4. Now, process P0 gets preempted before it sets the lock value to 1.

Scene-02:
Another process P1 arrives.
1. It executes the lock!=0 instruction.
2. Since lock value is still 0, so it returns value 0 to the while loop.
3. The while loop condition breaks.
4. It sets the lock value to 1 and enters the critical section.
5. Now, process P1 gets preempted in the middle of the critical section.
Scene-03:
Process P0 gets scheduled again.
1. It resumes its execution.
2. Before preemption, it had already failed the while loop condition.
3. Now, it begins execution from the next instruction.
4. It sets the lock value to 1 (which is already 1) and enters the critical section.
Thus, both the processes get to present inside the critical section at the same time.
Problem of Proposal -2: Lock Variables
Suppose that one process reads the lock and sees that it is 0. Before it can set the lock to 1, another process is
scheduled, runs, and sets the lock to 1. When the first process runs again, it will also set the lock to 1, and two
processes will be in their critical regions at the same time.
Now you might think that we could get around this problem by first reading out the lock value, then checking it again
just before storing into it, but that really does not help.

1. The race now occurs if the second process modifies the lock just after the first process has finished its second check.
2. No Mutual Exclusion

The characteristics of this synchronization mechanism are-


1. It can be used for any number of processes.
2. It is a software mechanism implemented in user mode.
3. There is no support required from the operating system.
4. It is a busy waiting solution which keeps the CPU busy when the process is actually waiting.
5. It does not fulfill any criteria of synchronization mechanism.

Proposal -3: Turn Variable or Strict Alternation Approach


1. Turn Variable or Strict Alternation Approach is the software mechanism implemented at user mode. It is a busy
waiting solution which can be implemented only for two processes.
2. In this approach, A turn variable is used which is actually a lock.
3. In strict alternation approach, Processes have to compulsorily enter the critical section alternately whether they
want it or not.

4
UNIT-2 OPERATING SYSTEMS, DEPT.OF CSE, ACOE, SURAMPALEM
4. This is because if one process does not enter the critical section, then other process will never get a chance to
execute again.
It is implemented as-

• Initially, turn value is set to 0.


• Turn value = 0 means it is the turn of process P0 to enter the critical section.
• Turn value = 1 means it is the turn of process P1 to enter the critical section.

Initially, two processes Pi and Pj are available and want to execute into critical section.
The turn variable is equal to i hence Pi will get the chance to enter into the critical section. The value of Pi remains I
until Pi finishes critical section.

Pi finishes its critical section and assigns j to turn variable. Pj will get the chance to enter into the critical section. The
value of turn remains j until Pj finishes its critical section.
Working-
This synchronization mechanism works as explained in the following scenes-
Scene-01:
1. Process P0 arrives.
2. It executes the turn!=0 instruction.
3. Since turn value is set to 0, so it returns value 0 to the while loop.
4. The while loop condition breaks.
5. Process P0 enters the critical section and executes.
6. Now, even if process P0 gets preempted in the middle, process P1 can not enter the critical section.
7. Process P1 can not enter unless process P0 completes and sets the turn value to 1.
Scene-02:
1. Process P1 arrives.
1. It executes the turn!=1 instruction.
2. Since turn value is set to 0, so it returns value 1 to the while loop.
3. The returned value 1 does not break the while loop condition.
4. The process P1 is trapped inside an infinite while loop.
5. The while loop keeps the process P1 busy until the turn value becomes 1 and its condition breaks.
Scene-03:
1. Process P0 comes out of the critical section and sets the turn value to 1.

5
UNIT-2 OPERATING SYSTEMS, DEPT.OF CSE, ACOE, SURAMPALEM
2. The while loop condition of process P1 breaks.
3. Now, the process P1 waiting for the critical section enters the critical section and execute.
4. Now, even if process P1 gets preempted in the middle, process P0 cannot enter the critical section.
5. Process P0 cannot enter unless process P1 completes and sets the turn value to 0.
Problem of Proposal -3: Turn Variable or Strict Alternation Approach

Analysis of Strict Alternation approach


1. Mutual Exclusion
The strict alternation approach provides mutual exclusion in every case. This procedure works only for two
processes. The pseudo code is different for both of the processes. The process will only enter when it sees that the
turn variable is equal to its Process ID otherwise not Hence No process can enter in the critical section regardless of
its turn.
2. Progress
Progress is not guaranteed in this mechanism. If Pi doesn't want to get enter into the critical section on its turn then
Pj got blocked for infinite time. Pj has to wait for so long for its turn since the turn variable will remain 0 until Pi
assigns it to j.
3. Portability
The solution provides portability. It is a pure software mechanism implemented at user mode and doesn't need any
special instruction from the Operating System.

Characteristics-
1. The characteristics of this synchronization mechanism are-
2. It ensures mutual exclusion.
3. It follows the strict alternation approach.
4. It does not guarantee progress since it follows strict alternation approach.
5. It ensures bounded waiting since processes are executed turn wise one by one and each process is guaranteed
to get a chance.
6. It ensures processes does not starve for the CPU.
7. It is architectural neutral since it does not require any support from the operating system.
8. It is deadlock free.
9. It is a busy waiting solution which keeps the CPU busy when the process is actually waiting.
Peterson's Solution
1. Peterson's Solution is a classic software-based solution to the critical section problem. It is unfortunately not
guaranteed to work on modern hardware, due to vagaries of load and store operations.
2. Peterson's solution is based on two processes
3. Suppose system contains more than two process then peterson’s solution not sufficient
4. Peterson's solution requires two shared data items:
int turn - Indicates whose turn it is to enter into the critical section. If turn = = i, then process i is allowed into their
critical section.
boolean flag[ 2 ] - Indicates when a process wants to enter into their critical section. When process i wants to enter
their critical section, it sets flag[ i ] to true.

The structure of process Pi in Peterson’s solution

6
UNIT-2 OPERATING SYSTEMS, DEPT.OF CSE, ACOE, SURAMPALEM
Proof: Mutual Exclusion

Bounded-Waiting
Case III: (Starvation)
P1 is executing its CS repeatedly
-upon exiting its CS, P1 sets flag [1] = false
-hence the while loop is false for P0 and it can go (sufficient?)
However, P1 may attempt to re-enter its CS before P0 has a chance to run.
- But to re-enter, P1 sets flag [1] to true and sets turn to 0
- Hence the while loop is true for P1 and it waits
- The while loop is now false for P0 and it can go
1. In the following diagram, the entry and exit sections are enclosed in boxes.
2. In the entry section, process i first raises a flag indicating a desire to enter the critical section.
3. Then turn is set to j to allow the other process to enter their critical section if process j so desires.
4. The while loop is a busy loop (notice the semicolon at the end), which makes process i wait as long as process j has
the turn and wants to enter the critical section.

7
UNIT-2 OPERATING SYSTEMS, DEPT.OF CSE, ACOE, SURAMPALEM
5. Process i lowers the flag[ i ] in the exit section, allowing process j to continue if it has been waiting.

Peterson’s Solution satisfy all three conditions:


1. Mutual Exclusion: Mutual exclusion is assured as only one process can access the Critical Section at any time. If both
processes attempt to enter at the same time, the last process to execute “turn = j” will be blocked.
2. Progress: Progress is also satisfied. A process outside the Critical Section does not blocks other processes from
entering the Critical Section. The flag variable allows one process to release the other when exiting their Critical
Section.
3. Bounded Waiting: Bounded waiting assure that each process will have to let the other process go first at most one
time before it becomes their turn again. Thus, bounded waiting is also assured as each process gets a fair chance.

Note that the instruction "turn = j" is atomic, that is it is a single machine instruction which cannot be interrupted.

Synchronization Hardware
• In general we can provide any solution to critical section problem by using a simple tool called as LOCK where we
can prevent the race condition.
• Many systems provide hardware support (hardware instructions available on several systems) for critical section
code.
• In UniProcessor hardware environment by disabling interrupts we can solve the critical section problem. So that
Currently running code would execute without any preemption.
• But by disabling interrupts on multiprocessor systems is time taking so that it is inefficient
compared to UniProcessor system.
• Now a days Modern machines provide special atomic hardware instructions that allow us to either test memory
word and set value Or swap contents of two memory words automatically i.e. Done through an uninterruptible unit.

Special Atomic hardware Instructions


• TestAndSet()
• Swap()
• The TestAndSet() Instruction is one kind of special atomic hardware instruction that allow us to test memory and
set the value.
• We can provide Mutual Exclusion by using TestAndSet() instruction.
• To implement Mutual Exclusion using TestAndSet() we need to declare Shared Boolean variable called as ‘lock’ (
initialized to false ) .
Test and Set Lock:
1. Test and Set Lock (TSL) is a synchronization mechanism.
2. It uses a test and set instruction to provide the synchronization among the processes executing concurrently.
Test-and-Set Instruction
1. It is an instruction that returns the old value of a memory location and sets the memory location value to 1 as a
single atomic operation.
2. If one process is currently executing a test-and-set, no other process is allowed to begin another test-and-set until
the first process test-and-set is finished.
It is implemented as-
1. Initially, lock value is set to 0.
2. Lock value = 0 means the critical section is currently vacant and no process is present inside it.
3. Lock value = 1 means the critical section is currently occupied and a process is present inside it.
do {
while (test and set(&lock)); /* do nothing */

8
UNIT-2 OPERATING SYSTEMS, DEPT.OF CSE, ACOE, SURAMPALEM
/* critical section */
lock = false;
/* remainder section */
} while (true );
boolean test and set(boolean *target)
{
boolean rv = *target;
*target = true;
return rv;
}

The characteristics of this synchronization mechanism are-


1. It ensures mutual exclusion.
2. It is deadlock free.
3. It does not guarantee bounded waiting and may cause starvation.
4. It is not architectural neutral since it requires the operating system to support test-and-set instruction.
5. It is a busy waiting solution which keeps the CPU busy when the process is actually waiting
1. The above examples satisfy the mutual exclusion requirement, but unfortunately do not guarantee bounded
waiting.
2. If there are multiple processes trying to get into their critical sections, there is no guarantee of what order they will
enter, and any one process could have to wait forever until they got their turn in the critical section.

Swap- Test And Set algorithm


1. Swap algorithm is a lot like the TestAndSet algorithm.
2. Instead of directly setting lock to true in the swap function, key is set to true and then swapped with lock.
3. So, again, when a process is in the critical section, no other process gets to enter it as the value of lock is true.
Mutual exclusion is ensured.
4. Again, out of the critical section, lock is changed to false, so any process finding it gets enter the critical section.
Progress is ensured. However, again bounded waiting is not ensured
void Swap (Boolean *a, Boolean *b)
{
boolean temp = *a;
*a = *b;
*b = temp:
}
while (true)
{
key = TRUE;
while ( key == TRUE)
Swap (&lock, &key );
// critical section
lock = FALSE;
// remainder section
}
Shared Boolean variable called as ‘lock’ is to be declared to implement Mutual Exclusion in
Swap() also, which is initialized to FALSE

9
UNIT-2 OPERATING SYSTEMS, DEPT.OF CSE, ACOE, SURAMPALEM
Mutual Exclusion with Sleep() and Wakeup()
1. when a processes wants to enter in its critical section , it checks to see if then entry is allowed.
2. If it is not, the process goes into tight loop and waits (i.e., start busy waiting) until it is allowed to enter. This approach
waste CPU-time.
3. Now look at some interprocess communication primitives is the pair of sleep-wakeup.
Sleep: It is a system call that causes the caller to block, that is, be suspended until some other process wakes it up.
Wakeup:It is a system call that wakes up the process. Both 'sleep' and 'wakeup' system calls have one parameter that
represents a memory address used to match up 'sleeps' and 'wakeups' .

The Bounded Buffer Producers and Consumers


The bounded buffer producers and consumers assumes that there is a fixed buffer size i.e., a finite numbers of slots
are available.
Statement:
To suspend the producers when the buffer is full, to suspend the consumers when the buffer is empty, and to make
sure that only one process at a time manipulates a buffer so there are no race conditions or lost updates.
As an example how sleep-wakeup system calls are used, consider the producer-consumer problem also known as
bounded buffer problem.
Two processes share a common, fixed-size (bounded) buffer. The producer puts information into the buffer and the
consumer takes information out.
Trouble arises when
The producer wants to put a new data in the buffer, but buffer is already full.
Solution: Producer goes to sleep and to be awakened when the consumer has removed data.

The consumer wants to remove data the buffer but buffer is already empty.
Solution: Consumer goes to sleep until the producer puts some data in buffer and wakes consumer up.

Mutex Locks
1. The hardware solutions presented above are often difficult for
ordinary programmers to access, particularly on multi-processor
machines, and particularly because they are often platform-
dependent.
2. Therefore most systems offer a software API equivalent called mutex
locks or simply mutexes. ( For mutual exclusion )
3. The terminology when using mutexes is to acquire a lock prior to
entering a critical section, and to release it when exiting

Solution to the critical-section problem using mutex locks

1. Just as with hardware locks, the acquire step will block the process if the lock is in use
by another process, and both the acquire and release operations are atomic.
2. Acquire and release can be implemented as shown here

3. One problem with the implementation is the busy loop used to block processes in
the acquire phase. These types of locks are referred to as spinlocks, because the CPU just sits and spins while
blocking the process.
4. Spinlocks are wasteful of cpu cycles, and are a really bad idea on single-cpu single-threaded machines, because
the spinlock blocks the entire computer, and doesn't allow any other process to release the lock.

10
UNIT-2 OPERATING SYSTEMS, DEPT.OF CSE, ACOE, SURAMPALEM
Semaphores
1. Semaphore a proposed by Edsgar Dijkstra is a technique to manage concurrent processes by using a simple inter
value, which is known as a semaphore.
2. A semaphore S is an integer variable which is non-negative and shared between threads. This variable is used to
solve the critical section problem and to achieve process synchronization in the multiprocessing
environment.
3. A semaphore S is an integer variable that, apart from initialization, is accessed only through two standard atomic
operations: wait() and signal().
1. The wait()  termed P (from the Dutch proberen, which means “to test”);
2. signal() was originally called V (from verhogen, which means “to increment”).

The definition of wait() is as follows:


wait(S)
{
while (S <= 0); // busy wait
S--;
}

The definition of signal() is as follows:


signal(S)
{
S++;
}
All modifications to the integer value of the semaphore in the wait() and signal() operations must be executed
indivisibly. That is, when one process modifies the semaphore value, no other process can simultaneously modify
that same semaphore value.

Semaphore Usage
Types of Semaphores:
1. The value of a binary semaphore can range only between 0 and 1. In some systems the Binary Semaphore is
called as Mutex locks, because, as they are locks to provide the mutual exclusion
2. The value of a counting semaphore can range over an unrestricted domain. Counting semaphores can be used to
control access to a given resource consisting of a finite number of instances
3. The process that wish to use a resource must performs the wait() operation ( count is decremented )
4. The process that releases a resource must performs the signal() operation ( count is incremented )
5. When the count for the semaphore is 0 means that all the resources are being used by some processes.
Otherwise resources are available for the processes to allocate.
6. When a process is currently using a resource means that it blocks the resource until the count becomes > 0.
For example:

1. Let us assume that there are two processes p0 and p1 which consists of two statements s0 & s1 respectively.
2. Also assume that these two processes are running concurrently such that process p1 executes the statement s1
only after process p0 executes the statement s0.

Semaphore Implementation with no Busy waiting

Implementation of wait: (definition of wait with no busy waiting)

11
UNIT-2 OPERATING SYSTEMS, DEPT.OF CSE, ACOE, SURAMPALEM
wait (S){
S.value=S.value-1;
if (S.value < 0) {
add this process to waiting queue
block(); }
}
Implementation of signal: (definition of signal with no busy waiting)
Signal (S){
S.value=S.value +1;
if (value <= 0) {
remove a process P from the waiting queue
wakeup(P); }
}

Disadvantages of Semaphores
1. While a process is in its critical section, any other process that tries to enter its critical section must loop
continuously in the entry code.
2. Busy waiting wastes CPU cycles that some other process might be able to use productivity
3. This type of semaphore is also called spinlock because the process “spins“ waiting for the lock.
4. To overcome the need for busy waiting, we can modify the definition of the wait () and signal () semaphore
operations.
5. When a process executes the wait () operation and finds that the semaphore value is not positive, it must
wait.
6. How rather than engaging in busy waiting, the process can block itself.
7. The block operation places a process into a waiting queue associated with the semaphore, and the state of
the process is switched to the waiting state.
8. The control is transferred to the CPU scheduler, which selects another process to execute.
Deadlocks and Starvation
The implementation of semaphore with waiting queue may result in the situation where
two or more processes are waiting for an event is called as Deadlocked.
• To illustrate this, let us assume two processes P0 and P1 each accessing two semaphores
S and Q which are initialized to 1 :-

1. Now process P0 executes wait(S) and P1 executes wait(Q), assume that P0 wants
to execute wait(Q) and P1 executes wait(S). But it is possible only after process P1
executes the signal(Q) and P0 executes signal(S).
2. Starvation or indefinite blocking. A process may never be removed from the semaphore queue in which it is
suspended.

Classical Problems of Synchronization


1. Bounded-Buffer Problem
2. Readers and Writers Problem
3. Dining-Philosophers Problem

The Bounded-Buffer Problem

12
UNIT-2 OPERATING SYSTEMS, DEPT.OF CSE, ACOE, SURAMPALEM
1. The bounded-buffer problem (Producer Consumer Problem) is one of the
classic problem of synchronization. Producer
2. There is a buffer of n slots and each slot is cable of storing one unit of Consumer
data..
3. There are two processes running namely Producer and Consumer, which
are operating on the buffer.
4. The producer tries to insert data into an empty slot of the buffer.
5. The consumer tries to remove data from a filled slot in the buffer. Buffer of n slots
1. The producer must not insert data when the buffer s full
2. The consumer must not remove data when the buffer is
empty
6. The Producer and Consumer should not insert and remove data simultaneously.
We will make use of three semaphores:
1. m(mutex), a binary semaphore which is used to acquire and release the lock.
2. empty, a counting semaphore whose initial value is the number of slots in the buffer since initially all slots are
empty.
3. Full ,counting semaphore whose initial value is 0.

The structure of the producer process.


do {
...
/* produce an item in next produced */
...
wait(empty); // wait until empty>0 and then decrement ‘empty’
wait(mutex); //acquire lock
...
/* add next produced to the buffer */
...
signal(mutex); //release lock
signal(full); //increment ‘full’
} while (true);

The structure of the consumer process.


do {
wait(full); // wait until full>0 and then decrement ‘full’
wait(mutex); //acquire lock
...
/* remove an item from buffer to next consumed */
...
signal(mutex); //release lock
signal(empty); //increment ‘empty’
...
/* consume the item in next consumed */
...
} while (true);

Readers-Writers Problem
1. A database is to be shared among several concurrent processes.
2. Some of these processes may want only to read the database, whereas others may want to update (that is, to
read and write) the database.

13
UNIT-2 OPERATING SYSTEMS, DEPT.OF CSE, ACOE, SURAMPALEM
3. We distinguish between these two types of processes by referring to the former as readers and to the latter as
writers.
4. if two readers access the shared data simultaneously, no adverse effects will result.
5. if a writer and some other process (either a reader or a writer) access the database simultaneously, chaos may
ensue.
6. To ensure that these difficulties do not arise, we require that the writers have exclusive access to the shared
database while writing to the database.
7. This synchronization problem is referred to as the readers–writers problem.
8. We will make use of two semaphores and an integer variable:
9. 1.mutex, a semaphore (initialized to 1) which is used to ensure mutual exclusion when readcount is upadated
i.e., when any reader enters or exit from the critical section.
10. 2.Wrt , a semphore (initialized to 1) common to both reader and writer processes.
11. 3.readcount , an integer variable (initialized to 0) that keeps tracks of how many processes are currently
reading the object.
12. The structure of a writer process.

do {
wait(mutex);
...
/* writing is performed */
...
signal(mutex);
} while (true);

The structure of a reader process


while (true) {
wait (mutex) ;
readcount ++ ; //The number of readers has now increased by 1
if (readcount == 1)
wait (wrt) ; //this ensure no writer can enter if there is even one reader
signal (mutex)
// reading is performed

wait (mutex) ;
readcount - - ; //a reader wants to leave
if (readcount == 0) // no reader is left in the critical section
signal (wrt) ; //writers can enter
signal (mutex) ; //reader leave
}
Dining-Philosophers Problem
1. Consider five philosophers who spend their lives thinking and eating.
2. When a philosopher thinks, she does not interact with her colleagues.
3. Philosopher gets hungry and tries to pick up the two chopsticks that are closest
to her left and right neighbors
4. A philosopher may pick up only one chopstick at a time.
5. Obviously, she cannot pick up a chopstick that is already in the hand of a
neighbour.
6. When a hungry philosopher has both her chopsticks at the
The situation of the dining philosophers.
same time, she eats without releasing the chopsticks.

14
UNIT-2 OPERATING SYSTEMS, DEPT.OF CSE, ACOE, SURAMPALEM
7. When she is finished eating, she puts down both chopsticks and starts thinking again
8. One simple solution is to represent each chopstick with a semaphore.
9. A philosopher tries to grab a chopstick by executing a wait() operation on that semaphore.
10. She releases her chopsticks by executing the signal() operation on the appropriate semaphores.
11. Thus, the shared data are semaphore chopstick[5];

The structure of Philosopher i:


While (true) {
wait ( chopstick[i] );
wait ( chopStick[ (i + 1) % 5] );
// eat
signal ( chopstick[i] );
signal (chopstick[ (i + 1) % 5] );
// think
}
1. Although this solution guarantees that no two neighbours are eating simultaneously, it nevertheless must be
rejected because it could create a deadlock.
2. Suppose that all five philosophers become hungry at the same time and each grabs her left chopstick.
3. All the elements of chopstick will now be equal to 0. When each philosopher tries to grab her right chopstick,
she will be delayed forever.
Several possible remedies to the deadlock problem are replaced by:

• Allow at most four philosophers to be sitting simultaneously at the table.

• Allow a philosopher to pick up her chopsticks only if both chopsticks are available (to do this, she must pick them
up in a critical section).

• Use an asymmetric solution—that is, an odd-numbered philosopher picks up first her left chopstick and then her
right chopstick, whereas an even numbered philosopher picks up her right chopstick and then her left chopstick.

Problems with Semaphores


Incorrect use of semaphore operations:
– signal (mutex) …. wait (mutex) Case 1
– wait (mutex) … wait (mutex) Case 2
– Omitting of wait (mutex) or signal (mutex) (or both) Case 3
• As the semaphores used incorrectly as above may results the timing errors.
• Case 1 Several processes may execute in critical section by violating the mutual exclusion requirement.
• Case 2 Dead lock will occur.
• Case 3 either mutual exclusion is violated or dead lock will occur
• To deal with such type of errors, researchers have developed high-level language constructs.
• One type of high-level language constructs that is to be used to deal with the above type of errors
is the Monitor type.

Monitors
A high-level abstraction that provides a convenient and effective mechanism for process synchronization.
• A procedure can access only those variables that are declared in a monitor and formal parameters
• Only one process may be active within the monitor at a time

15
UNIT-2 OPERATING SYSTEMS, DEPT.OF CSE, ACOE, SURAMPALEM
Syntax of the monitor :-
monitor monitor-name
{
// shared variable declarations
procedure P1 (…) { …. }

Schematic view of a Monitor
procedure Pn (…) {……}
Initialization code ( ….) { … }

}
Dining-Philosophers Solution Using Monitors
1. This solution to the dining philosophers uses monitors, and the restriction that a philosopher may only pick
up chopsticks when both are available. There are also two key data structures in use in this solution:
2. enum { THINKING, HUNGRY,EATING } state[ 5 ];
3. A philosopher may only set their state to eating when neither of their adjacent neighbors is eating.
1. ( state[ ( i + 1 ) % 5 ] != EATING && state[ ( i + 4 ) % 5 ] != EATING ).
4. condition self[ 5 ]; This condition is used to delay a hungry philosopher who is unable to acquire chopsticks.
5. In the following solution philosophers share a monitor, DiningPhilosophers, and eat using the following
sequence of operations:
6. DiningPhilosophers.pickup( ) - Acquires chopsticks, which may block the process. eat
7. DiningPhilosophers.putdown( ) - Releases the chopsticks.

16
UNIT-2 OPERATING SYSTEMS, DEPT.OF CSE, ACOE, SURAMPALEM

You might also like