Chapter-2 (OS) Continued
Chapter-2 (OS) Continued
Critical Section:
When more than one threads try to access the same code segment
that segment is known as the critical section. The critical section
contains shared variables or resources that need to be
synchronized to maintain the consistency of data variables.
In simple terms, a critical section is a group of
instructions/statements or regions of code that need to be
executed atomically.
In concurrent programming, if one thread tries to change the value
of shared data at the same time as another thread tries to read the
value (i.e., data race across threads), the result is unpredictable.
The access to such shared variables (shared memory, shared files,
shared port, etc.) is to be synchronized.
Initialization of semaphores –
mutex = 1 //binary semaphore
Full = 0 // Initially, all slots are empty. Thus full slots are 0
Empty = n // All slots are empty initially.
Readers-Writers Problem
Consider a situation where we have a file shared between many
people.
If one of the person tries editing the file, no other person
should be reading or writing at the same time, otherwise
changes will not be visible to him/her.
However, if some person is reading the file, then others
may read it at the same time.
Writer process:
1. Writer requests the entry to critical section.
2. If allowed i.e. wait() gives a true value, it enters and
performs the write. If not allowed, it keeps on waiting.
3. It exits the critical section.
do {
// writer requests for critical section
wait(wrt);
Reader process:
1. Reader requests the entry to critical section.
2. If allowed:
it increments the count of number of readers inside
the critical section. If this reader is the first reader
entering, it locks the wrt semaphore to restrict the
entry of writers if any reader is inside.
It then, signals mutex as any other reader is
allowed to enter while others are already reading.
After performing reading, it exits the critical
section. When exiting, it checks if no more reader
is inside, it signals the semaphore “wrt” as now,
writer can enter the critical section.
3. If not allowed, it keeps on waiting.
do {
// Reader wants to enter the critical section
wait(mutex);
readcnt--;