Skip to content

Instantly share code, notes, and snippets.

@whyrusleeping
Created March 29, 2013 23:26
Show Gist options
  • Save whyrusleeping/5274366 to your computer and use it in GitHub Desktop.
Save whyrusleeping/5274366 to your computer and use it in GitHub Desktop.
Reader Writer lock implementation from Isilon interview.
typedef struct RWLock {
int readers;
bool writer;
bool writeRequest;
}
void LockForRead(RWLock *l) {
m.Lock();
while(l->writer || l->writeRequest) {
m.Unlock();
Sleep(10);
m.Lock();
}
om.Lock();
l->readers++;
om.Unlock();
m.Unlock();
}
void LockForWrite(RWLock *l) {
m.Lock();
l->writeRequest = true;
while(l->readers > 0 && l->writer) {
m.Unlock();
Sleep(10);
m.Lock();
}
l->writer = true;
l->writeRequest = false;
m.Unlock();
}
void UnlockForRead(RWLock *l) {
om.Lock();
l->readers--;
om.Unlock();
}
void UnlockForWrite(RWLock *l) {
m.Lock();
l->writer = false;
m.Unlock();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment