Mutex Locks

  • Mutex is short for mutual exclusion.
  • We use the mutex lock to protect critical regions and thus prevent race conditions.
  • That is, a process must acquire the lock before entering a critical section; it releases the lock when it exits the critical section.

A mutex lock has a boolean variable available whose value indicates if the lock is available or not. If the lock is available, a call to acquire() succeeds, and the lock is then considered unavailable. A process that attempts to acquire an unavailable lock is blocked until the lock is released.

Mutex locks are often implemented using one of the hardware mecha- nisms

struct Mutex {
    bool isLocked;
    owner;
    blocked_threads
}

// Mutex functions
acquire() {
    while (!available)
    ; /* busy wait */
    available = false;
}

release() {
    available = true;
}
do {
    // aquire lock
    // critical section
    // release lock
} while (true);

Condition Variables

// consumer: print and clear
Lock(m) {
    while(m_list.not_full())
Wait(m, list_full)
    m_list.print_and_remove_all()
}
// unlock

// producers: safe insert
Lock(m) {
    m_list.insert(thread_id);
    if (list is full)
        Signal(list_full)
}
// unlock

Wait(mutex, condition)

  • mutex is automatically released & required on wait

Signal(condition)

  • notify one thread waiting on condition

Broadcast(condition)

  • notify all threads

results matching ""

    No results matching ""