The way these work is as follows:
Read-Write locks actually contain 2 locks, a read lock and a write lock. The write lock is set when a process/thread is writing, while the read lock is incremented when a process/thread is reading, and decremented when done.
To avoid reading while the data is being written, a reader gets the write lock. Once the lock is gotten, the read lock is incremented and the write lock is released again. This way, the write lock is only set for a very short time amount of time.
To avoid writing while the data is being read, a writer first gets the write lock. This will prevent any new reader to continue reading the data. The writer then waits until the reader lock decrements to 0, meaning that all readers who had the lock before the write lock was gotten, finish reading. After this, the data is modified, and then the write lock is released again, allowing the readers who were waiting for the write lock to continue their processing.
Here's the code for it (I won't add the implementation for the get_lock and release_lock function, to save space, and because I am lazy to write it here).
The Lock structure is easy, it basically looks like this:
typedef struct {
volatile int read;
volatile int write;
} rwlock_t;
void rwlock_get_rd(rwlock_t *lock)
{
get_lock(&(lock->wr));
lock->rd += 1;
release_lock(&(lock->wr));
}
void rwlock_release_rd(rwlock_t *lock)
{
lock->rd -= 1;
}
void rwlock_get_wr(rwlock_t *lock)
{
get_lock(&(lock->wr));
get_lock_no_set(&(lock->rd));
}
void rwlock_release_wr(rwlock_t *lock)
{
release_lock(&(lock->wr));
}
______________________________________________________________________________ Reader 1 | RD | -========= -========== -=========== | WR | -= -= -------------= ______________________________________________________________________________ Reader 2 | RD | -========= -=========== -=========== | WR | --= -= ------------= ______________________________________________________________________________ Reader 3 | RD | -========= -=========== -=========== | WR | -= -= ------------= ______________________________________________________________________________ Writer | RD | ---------============= | WR | -====================== ______________________________________________________________________________ - thread waits for lock = thread has lock
No comments:
Post a Comment