Advantages of Reader/Writer locks on small single-core systems.
Written 2012-09-23
Tags:Latency reader-writer-lock contention semaphore lock
Most commonly, reader/writer locks are applied to larger systems where it can decrease contention when there are many threads trying to read. In my case there were actually very few threads, but a reader/writer lock still proved advantageous. Let us examine what can happen when two threads need to read, using both a standard lock, and a reader/writer lock.
Premise: Thread A is high-priority, thread B is low-priority, and the OS provides hard-priority-scheduling. Only these two threads will run in the period of time we're interested in.
Here's what could happen using a single standard lock.
- An event occurs, causing thread B to run.
- Thread B takes the lock and begins reading
- An event occurs, causing thread A to run.
- A context-switch occurs due to thread-priority. Thread A is now running.
- Thread A attempts to read but is blocked.
- A context-switch occurs, allowing thread B to release the lock.
- A context-switch occurs due to thread-priority. Thread A is now running.
- Thread A takes the lock, reads, unlocks, and blocks elsewhere.
- A Context switch occurs due to only one ready-to-run thread.
- Thread B continues until it blocks elsewhere.
But now, lets look at what happens with a reader/writer lock instead, with similar event timing.
- An event occurs, causing thread B to run.
- Thread B takes the lock and begins reading
- An event occurs, causing thread A to run.
- A context-switch occurs due to thread-priority. Thread A is now running.
- Thread A also takes the lock, reads, and releases the lock. It then blocks elsewhere.
- Thread B finishes reading, releases the lock, and blocks elsewhere.
First we notice that using the reader/writer lock avoids a pair of unceccesary context-switches. This is nice, but the advantage is heavily architecture/OS dependent.
Even assuming the context-switches are cheap, there's another advantage to the reader/writer lock in this situation. The advantage is system latency - by using the reader/writer lock instead of a simple lock, high-priority threads no longer have to wait for low-priority thread to release the lock. The ability to allow multiple threads to enter the critical section is the same reason it is often chosen in high-contention environments, but it also usefully provides reduced latency when experiencing any contention.