Lec 3-3 CENG328 IPC-2
Lec 3-3 CENG328 IPC-2
Bounded(N places)-Buffer
Readers and Writers
Classical Synchronization
Dining-Philosophers
Problems
Sleeping Barber
Dining-Philosophers Problem
Solution using monitors
Each of N buffer places can hold one data item The structure of the producer process
Implementation: do {
Use binary semaphore mutex to establish // produce an item
mutual exclusion on buffer update, initialized wait (empty); // queued if 0
to 1 wait (mutex);
Use a multi-value semaphore full to // add the item to the buffer
implement item consumption, initialized to 0 signal (mutex);
Use a multi-value semaphore empty to signal (full); //allow consumer to consume if any
implement item production, initialized N. } while (true);
The structure of the consumer process A data set is shared among a number of concurrent reader and writer
processes
do { Readers – only read the data set; they do not perform any updates
wait (full); //queue if 0 Writers – write the data item to be read by the readers
Design algorithm:
wait (mutex);
multiple readers can read an item, if exist, concurrently with no protection
// remove an item from buffer Writer(s) can only write data item in mutual exclusion
signal (mutex); A writer and a reader can write and read in mutual exclusion
Modeling Shared Data
signal (empty); //allow producer to produce, if any
Data set: item
// consume the removed item Semaphore mutex initialized to 1
} while (true); Semaphore wrt initialized to 1
Integer readcount is readers shared memory, initialized to 0: it counts
number of readers in the process of reading.
1
Readers-Writers Problem (Cont.) Readers-Writers Problem (Cont.)
writer process: should write only if there is no active The structure of a reader process
reader do {
wait (mutex) ;
do { readcount ++ ;
wait (wrt) ; // no limit on number of items if (readercount == 1) wait (wrt) ;
signal (mutex)
wait (mutex) ;
signal (wrt) ; readcount - - ;
} while (true) if redacount == 0) signal (wrt) ;
signal (mutex) ;
} while (true)
Dining-Philosophers Problem: 5
philosopher dine and think
Dining Philosophers: First Try
2
The Sleeping Barber Problem (2)
Sleeping Barber
3
Solution to Dining Philosophers: Monitor
Monitor with Condition Variables Solution
monitor DiningPhilosopher
{
enum { THINKING; HUNGRY, EATING) state [5] ;
condition self [5];
void pickup (int i) {
state[i] = HUNGRY;
test(i);
if (state[i] != EATING) self [i].wait;
}
void putdown (int i) {
state[i] = THINKING;
// test left and right neighbors
test((i + 4) % 5);
test((i + 1) % 5);
}
void *functionC();
pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
int counter = 0;
main()
{
Compile: gcc -lpthread mutex1.c
int rc1, rc2;
Run:
pthread_t thread1, thread2;
void *functionC()
{
pthread_mutex_lock( &mutex1 );
counter++;
printf("Counter value: %d\n",counter);
pthread_mutex_unlock( &mutex1 );
}
4
THIS IS ALL ABOUT THREADS!
Operating Systems