Docsity

Operating Systems: Synchronization Mechanisms - Semaphores - Prof. Gregory D. Benson, Exams of Operating Systems

Toggle sidebar
bg1
CS 326
Operating Systems
Synchronization
Greg Benson
Department of Computer Science
University of San Francisco
High-level Synchronization
•So far we have seen low-level mechanisms for
synchronization (mutual exclusion):
•Disabling interrupts on uniprocessors
•Spinlocks (test-and-set) on multiprocessors
•We will now look at higher-level mechanisms:
•Semaphores
•Monitors
2
Semaphores
•Special kind of variable (s)
•A non-negative integer with atomic increment and decrement
•Two operations
•P(s) or down(s)
•Decrement counter, if counter is 0 then block
•V(s) or up(s)
•Increment counter and wake one blocked thread
3
Semaphores - Formal Def
•Let nP = number of completed P operations on s
•Let nV = number of completed V operations on s
•Let initVal = initial value of s
•Require: nP <= nV + initVal
•If s = (nV + initVal) - nP, then
•Invariant: s >= 0
4
Semaphore Implementation
•First, a busy-waiting implementation:
5
int sem;
down(int *s) {
int acquired = 0;
while (!acquired) {
disable_preemption();
if (*s > 0) {
*s--; acquired = 1;
}
enabled_preemption();
}
}
up(int *s) {
disable_preemption();
*s++;
enable_preemption();
}
Semaphore Implementation 2
•Now, a blocking implementation:
6
struct sem {int value, list_elem list};
down(struct sem *s) {
disable_preemption();
if (s->value == 0) {
listadd(cur, s->list);
thread_block();
} else {
s->value--;
}
enabled_preemption();
}
up(int *s) {
disable_preemption();
if (!listempty(s->list)
thread_unblock(listremove(s->list));
else
! *s++;
enable_preemption();
}
pf3
pf4
pf5

Partial preview of the text

Download Operating Systems: Synchronization Mechanisms - Semaphores - Prof. Gregory D. Benson and more Exams Operating Systems in PDF only on Docsity!

CS 326

Operating Systems

Synchronization

Greg Benson

Department of Computer Science

University of San Francisco

High-level Synchronization

• So far we have seen low-level mechanisms for

synchronization (mutual exclusion):

• Disabling interrupts on uniprocessors

• Spinlocks (test-and-set) on multiprocessors

• We will now look at higher-level mechanisms:

• Semaphores

• Monitors

2

Semaphores

• Special kind of variable (s)

• A non-negative integer with atomic increment and decrement

• Two operations

• P(s) or down(s)

• Decrement counter,^ if counter is 0 then block

• V(s) or up(s)

• Increment counter and wake one blocked thread

3

Semaphores - Formal Def

• Let nP = number of completed P operations on s

• Let nV = number of completed^ V operations on s

• Let initVal = initial value of s

• Require:^ nP <= nV + initVal

• If s = (nV + initVal) - nP,^ then

• Invariant:^ s >= 0

4

Semaphore Implementation

• First,^ a busy-waiting implementation:

int sem; down(int s) { int acquired = 0; while (!acquired) { disable_preemption(); if (s > 0) { *s--; acquired = 1; } enabled_preemption(); } } up(int *s) { disable_preemption(); *s++; enable_preemption(); }

Semaphore Implementation 2

• Now,^ a blocking implementation:

struct sem {int value, list_elem list}; down(struct sem *s) { disable_preemption(); if (s->value == 0) { listadd(cur, s->list); } else {^ thread_block(); }^ s->value--; enabled_preemption(); } up(int disable_preemption(); s) { if (!listempty(s->list) else^ thread_unblock(listremove(s->list)); ! (^) enable_preemption();s++; }

Semaphore Implementation 3

  • The Pintos blocking implementation: 7 struct sem {int value, list_elem list}; down(struct disable_preemption(); sem s) { while (s->value listadd(cur, s->list); == 0) { / allow for higher priority threads / }^ thread_block(); / disable preemption^ */ ! s->value--; }^ enabled_preemption(); up(int disable_preemption(); s) { if (!listempty(s->list) thread_unblock(listremove(s->list)); ! (^) enable_preemption();s++; } Types of Semaphores
  • Counting semaphore:^ semaphore with any value >= 0
  • Used for scheduling
  • Binary semaphore:^ semaphore with only two values (0 or 1)
  • Used for mutual exclusion and scheduling 8 Semaphores in Practice
  • Not too low-level and not too high-level
  • Often used in OS kernels to build even high- level synchronization
  • E.g.,^ Pintos uses semaphores to implement locks!
  • Very flexible 9 Semaphore Examples
  • We will look at three example uses of semaphores:
  • Mutual exclusion
  • Bounded buffer
  • Dining philosophers 10 Semaphore Mutual Exclusion
  • Use a binary semaphore as a lock variable int counter; struct semaphore c_mutex; sema_init(&c_mutex, 1); thread: ! ! sema_down(&c_mutex); /* enter CS / counter++; sema_up(&c_mutex); / leave CS */ Semaphore Bounded Buffer
  • Also called producer-consumer problem int buf[N], front = 0; rear = 0; struct semaphore mutex, full, empty; sema_init(&mutex, 1); sema_init(&full, 0), sema_init(&empty, N); Producer Thread: /* produce item / / wait for empty slot / ! sema_down(&empty); sema_down(&mutex); / put item in buffer / buf[rear] = item; rear = (rear + 1) % N; sema_up(&mutex); / announce item in buf / sema_up(&full); Consumer Thread: / wait for item / ! sema_down(&full); sema_down(&mutex); / put item in buffer / item = buf[front]; front = (front + 1) % N; sema_up(&mutex); / announce free slot / sema_up(&empty); / consume item */

Monitor Implementation

  • Entry Queue - queue of threads that wish to enter the monitor
  • CV Queue - one queue for each condition variable
  • wait(cv)^ - wait outside monitor on cv queue
  • signal(cv)^ - wake up thread,^ put on entry queue
  • This is just one possible implementation 19 Monitor Shared variables EntryQ Only one thread at a time cv1Q cv2Q Comparison to Semaphores
  • Differences between^ wait()/signal() and P()/V()
  • a^ signal()^ is not remembered if no thread is on the cv queue
  • V()^ operations are remembered (why?)
  • Unlike^ P(),^ wait()^ always blocks the executing thread 20 Comparison to Java
  • Java class can act like monitor with one (implicit) condition variable
  • Java has a^ wait()^ operation
  • Java has a^ notify()^ operation instead of signal()
  • To use Java monitors you must declare methods as synchronized (or use the synchronized statement) 21 Monitor Examples
  • Mutual exclusion
  • Bounded buffer
  • Dining philosophers
  • Readers-writers 22 Monitor Mutual Exclusion
  • Monitors have implicit mutual exclusion to monitor shared variables
  • Can implement mutual exclusion locks with monitors monitor mutex { ! int locked = FALSE; ! condition busy; ! void enter(void) { !! if (locked) wait(busy); !! locked = TRUE; ! } ! void exit(void) { !! locked = FALSE; !! signal(busy); ! } } Thread: ! ... ! mutex.enter(); ! /* in CS */ ! mutex.exit(); ! ... Monitor Bounded Buffer monitor buffer { ! int buf[N]; ! int front=0, rear=0, count=0; ! condition not_full, not_empty; ! void deposit(int data) { !! if (count == N) wait(not_full); !! buf[rear] = data; !! rear = (rear + 1) % N; !! count++; !! signal(not_empty); ! } ! int fetch(void) { !! !! int rv;if (count == 0) wait(not_empty); !! rv = buf[front]; !! front = (front + 1) % N; !! count--; !! signal(not_full); !! return rv; ! } } Producer Thread: ! ... ! buffer.deposit(item); ! ... Consumer Thread: ! .... !! item.... = buffer.fetch();

Monitor Dining Philosophers 25 monitor! int forks[N] = dp { {2, 2, ..., 2}; ! condition both_free[N]; ! /* right[i] is i’s right neighbor / ! int right[N] = {1, ..., N-1, 0}; ! / left[i] is i’s left neighbor / ! int left[N] = {N-1, 0, 1, ..., N-2}; ! void getforks(int i) { !! !! if (forks[i]forks[right[i]]--; < 2) wait(both_free); !! forks[left[i]]--; ! } ! void relforks(int i) { !! forks[right[i]]++; !! forks[left[i]]++; !! if (forks[right[i]] == 2) !!! signal(both_free[right[i]]); !! !! if (forks[left[i]]! signal(both_free[left[i]]); == 2) ! } } Philosopher! Thread i: ! while(1) { !! / Think / !! ... !! dp.getforks(i); !! / Eat */ !! dp.relforks(i); ! } Readers-Writers Problem

  • We have shared data or a shared database
  • Two types of threads:
    • Readers of shared data
    • Writers of shared data
  • Want to allow multiple readers to access the shared data simultaneously
  • Want to only allow a single writer to modify the data (no readers or other writers) 26 Monitor Readers-Writers 27 monitor rw { ! int nr = 0, nw = 0; ! condition OKR, OKW; ! void req_read(void) { !! if (nw > 0) wait(OKR); !! nr++; !! signal(OKR); ! } ! void rel_read(void) { !! nr--; !! if (nr = 0) signal(OKW); !! }void req_write(void) { !! if (nr > 0 || nw > 0) wait(OKW); !! nw++; ! } ! void rel_write(void) { !! nw--; !! if (!empty(OKW)) signal(OKW); !! if (!empty(OKR)) signal(OKR); ! } } Reader Thread: ! rw.req_read(); ! read shared_data ! rw.rel_read(); Writer Thread: ! rw.req_write(); ! modify shared data ! rw.rel_write(); Monitors in C
  • C does not have language support for threads and synchronization
  • We can achieve monitor-like functionality with locks and condition variables
  • In Pthreads:
    • Use mutex locks and condition variables
  • In Pintos:
    • Use locks and condition variables 28 Monitors in C Continued
  • Basic idea
  • Declare a single lock/mutex for each monitor (e.g.,^ buflock)
  • Declare variables/structs to associate with the monitor
  • Declare condition variables to associate with the monitor
  • For each monitor function,^ first acquire the monitor lock,

release on exit

  • Use the monitor lock as a parameter to cond_wait():
    • (Pthreads) pthread_cond_wait(&cv,^ &buflock)
    • (Pintos) cond_wait(&cv,^ &buflock) Monitors in C Example
  • Bounded buffer in C struct bbuf { ! struct mutex m; ! struct condition not_full, not_empty; ! int buf[N]; ! int count, front, rear; }; void bb_put(struct bbuf *b, int data) { ! lock_acquire(&(b->m)); ! if (count == N) wait(&(b->not_full), &(b->m)); ! b->buf[b->rear] = data; ! b->rear = (b->rear + 1) % N; ! count++; ! signal(&(b->not_empty)); ! lock_release(&(b->m)); }