30 lines
1.3 KiB
Markdown
Raw Permalink Normal View History

2015-12-26 14:17:24 +08:00
---
layout: pattern
title: Reader Writer Lock
folder: reader-writer-lock
2015-12-26 14:17:24 +08:00
permalink: /patterns/reader-writer-lock/
2016-07-21 09:27:48 +03:00
categories: Concurrency
2015-12-26 14:17:24 +08:00
tags:
2016-07-21 09:27:48 +03:00
- Performance
2015-12-26 14:17:24 +08:00
---
## Intent
2015-12-26 14:17:24 +08:00
Suppose we have a shared memory area with the basic constraints detailed above. It is possible to protect the shared data behind a mutual exclusion mutex, in which case no two threads can access the data at the same time. However, this solution is suboptimal, because it is possible that a reader R1 might have the lock, and then another reader R2 requests access. It would be foolish for R2 to wait until R1 was done before starting its own read operation; instead, R2 should start right away. This is the motivation for the Reader Writer Lock pattern.
## Class diagram
2015-12-26 14:17:24 +08:00
![alt text](./etc/reader-writer-lock.png "Reader writer lock")
## Applicability
2015-12-26 14:17:24 +08:00
Application need to increase the performance of resource synchronize for multiple thread, in particularly there are mixed read/write operations.
## Real world examples
2015-12-26 14:17:24 +08:00
* [Java Reader Writer Lock](https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/locks/ReadWriteLock.html)
## Credits
2015-12-26 14:17:24 +08:00
* [Readerswriter lock](https://en.wikipedia.org/wiki/Readers%E2%80%93writer_lock)
* [Readerswriters_problem](https://en.wikipedia.org/wiki/Readers%E2%80%93writers_problem)