Skip to content

Instantly share code, notes, and snippets.

@zhjgithub
Last active December 10, 2018 14:12
Show Gist options
  • Save zhjgithub/b00fb851341539162f2f500ef31a099b to your computer and use it in GitHub Desktop.
Save zhjgithub/b00fb851341539162f2f500ef31a099b to your computer and use it in GitHub Desktop.
Multiple readers and single writer lock
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++;
} // unlock
// ... read data ...
Lock(counter_mutex) {
resource_counter--;
if(resource_counter == 0)
Signal(write_phase);
} // unlock
// WRITER
Lock(counter_mutex) {
while(resource_counter != 0)
Wait(counter_mutex, write_phase);
resource_counter = -1;
} // unlock
// ... write data ...
Lock(counter_mutex) {
resource_counter = 0;
} // unlock
// avoid spurious wake-ups
Broadcast(read_phase);
Signal(write_phase);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment