Lecture 07
Lecture 07
Examples
Outline
while (true) {
...
/* produce an item in next_produced */
...
wait(empty);
wait(mutex);
...
/* add next produced to the buffer */
...
signal(mutex);
signal(full);
}
Bounded Buffer Problem (Cont.)
The structure of the consumer process
while (true) {
wait(full);
wait(mutex);
...
/* remove an item from buffer to next_consumed */
...
signal(mutex);
signal(empty);
...
/* consume the item in next consumed */
...
}
Readers-Writers Problem
A data set is shared among a number of concurrent processes
• Readers – only read the data set; they do not perform any
updates
• Writers – can both read and write
Problem – allow multiple readers to read at the same time
• Only one single writer can access the shared data at the same
time
Several variations of how readers and writers are considered – all
involve some form of priorities
Readers-Writers Problem (Cont.)
Shared Data
• Data set
• Semaphore rw_mutex initialized to 1
• Semaphore mutex initialized to 1
• Integer read_count initialized to 0
Readers-Writers Problem (Cont.)
while (true) {
wait(rw_mutex);
...
/* writing is performed */
...
signal(rw_mutex);
}
Readers-Writers Problem (Cont.)
signal (chopstick[i] );
signal (chopstick[ (i + 1) % 5] );
}
What is the problem with this algorithm?
Monitor Solution to Dining Philosophers
monitor DiningPhilosophers
{
enum { THINKING, HUNGRY, EATING) state [5] ;
condition self [5];
initialization_code() {
for (int i = 0; i < 5; i++)
state[i] = THINKING;
}
}
Solution to Dining Philosophers (Cont.)
Each philosopher “i” invokes the operations pickup() and
putdown() in the following sequence:
DiningPhilosophers.pickup(i);
DiningPhilosophers.putdown(i);
atomic_t counter;
int value;
POSIX Synchronization
POSIX API provides
• mutex locks
• semaphores
• condition variable
Widely used on UNIX, Linux, and macOS
POSIX Mutex Locks
Creating and initializing the lock
Another process can access the semaphore by referring to its name SEM.
Acquiring and releasing the semaphore:
POSIX Unnamed Semaphores
Creating an initializing the semaphore:
Usage:
Java Condition Variables
Condition variables are associated with an ReentrantLock.
Creating a condition variable using newCondition() method of
ReentrantLock: