Readers/Writer Problem

To ensure that these difficulties do not arise, we require that the writers have exclusive access to the shared database while writing to the database.

Readers/Writers Implementation

Mutex counter_mutex;
Condition read_phase, write_phase;
int resource_counter = 0;

// Readers
Lock(counter_mutex) {
    while(resource_counter == -1) {
        Wait(counter_mutex, read_phase);
    }
    resource_counter += 1;
} // unlock

// ... read ....

Lock(counter_mutex) {
    resource_counter -= 1;
    if (readers == 0)
        Signal(write_phase);
} // unlock

// Writer
Lock(counter_mutex) {
    while(resouce_counter != 0) 
        Wait(counter_mutex, write_phase);
    resource_counter +=1 ;
} // unlock

// ... write data

Lock(counter_mutex) {
    resource_counter = 0;
    Broadcast(read_phase);
    Signal(write_phase);
} // unlock

Critical Section Structure

Common Pitfalls

  • Keep track of mutex/condition variables used with a resource
  • Check that you are always (and correctly) using lock & unlock
  • Use a single mutex to access a single resource.
  • Check that you are signaling correct condition
  • Check that you are not using signal when broadcast is needed

results matching ""

    No results matching ""