Operating Systems

Table of Contents

Race conditions & mutual exclusion

programs can race each other and come to wrong conclusions.

Mutual exclusion

critical region: a code region with access to shared resources

the conditions for mutual exclusion:

  1. no two processes can be simultaneously in their critical regions
  2. no assumptions can be made about speed/number of CPUs
  3. no process running outside critical region may block others
  4. no process should have to wait forever to enter critical region

non-solutions

Peterson’s algorithm

#define N 2
int turn;
int interested[N];

void enter_region(int process){
    int other = 1 - process;
    interested[process] = TRUE;
    turn = process;
    while(turn==process && interested[other]==TRUE);
}

void leave_region(int process) {
    interested[process] = FALSE;
}

TSL instruction

enter_region:
TSL REGISTER, LOCK    | copy LOCK to register, set LOCK to 1
CMP REGISTER, #0      | was LOCK zero?
JNE ENTER_REGION      | if it was non-zero LOCK was set, so loop
RET                   | return to caller; critical region entered

leave_region:
MOVE LOCK, #0         | store a 0 in LOCK
RET                   | return to caller

Avoiding busy waiting

so far, CPU busy waits until it can enter the critical region (spin lock). so, let process waiting return CPU to scheduler voluntarily.

void sleep() {
    set own state to BLOCKED;
    give CPU to scheduler;
}

void wakeup(process) {
    set state of process to READY;
    give CPU to scheduler;
}

Producer-consumer

screenshot.png

Semaphores

screenshot.png

Monitors

screenshot.png

Message passing: solution to process sync and communication