Docsity

Semaphores in Operating Systems - Understanding Mutexes and Synchronization, Slides of Operating Systems

Partial preview of the text

Download Semaphores in Operating Systems - Understanding Mutexes and Synchronization and more Slides Operating Systems in PDF only on Docsity!

Topic#

Semaphores

Dr. Shariq BASHIR

Foundation University

Islamabad

Operating Systems

FALL 2019

Synchronization related

definitions

Atomic operation: operation always

execute to complete, or not at all.

Can't be stopped in the middle.

Semaphore

  • (^) Semaphore S , a integer variable, stored in the Operating System address space, shared by processes
  • (^) Provides Two standard operations to modify S: wait() and signal()
    • (^) Originally called P() and V()
  • (^) Can only be accessed via two indivisible (atomic) operations wait () / P() { while S <= 0; // no-op S--; } An atomic operation that waits for semaphore to become positive then decrements it by 1 signal () / V() { S++; } An atomic operation that increments semaphore by 1; wakes up a waiting P, if any Atomic Atomic

Semaphores for Programming

Languages

  • (^) Java
    • (^) java.util.concurrent.Semaphore
    • (^) Semaphore available = new
Semaphore(1);
  • (^) C/C++ (linux)
    • (^) #include <semaphore.h>
    • (^) sem_t mutex;

Two uses of Semaphores

  • (^) Mutual exclusion  (^) When semaphores are used for mutual exclusion: “One process in Critical Section” Semaphore mutex = 1; do { mutex.P(); // Critical Section mutex.V(); } while (TRUE); wait () / P() { while S <= 0; // no-op S--; } signal () / V() { S++; }

Semaphore as Mutual

Exclusion

Printer Pool

^ 

P()

V()

Semaphore for Scheduling

Constraints

Consumer

Consumer

Consumer

P()

V()

Producer

Semaphore Implementation with no Busy waiting

  • (^) With each semaphore there is an associated waiting queue.
  • (^) Two operations:
    • (^) block – place the process invoking the operation on the appropriate waiting queue.
    • (^) wakeup – remove one of processes in the waiting queue and place it in the ready queue.

Semaphore V()

Implementation

Printer Pool

Running

If Block Queue Not Empty Remove a Process from the Block Queue

V()

values ++;

V() should be atomic Disable Interrupts Enable Interrupts Change Status from Block to Ready

Ready

Binary and Counting

Semaphores

 (^) There are two kinds of Semaphores:  (^) Binary semaphores » (^) Control access to a single resource, taking the value of 0 (resource is in use) or 1 (resource is available).  (^) Counting semaphores » (^) Control access to multiple resources, thus assuming a range of nonnegative values. 14