---
name: read-write-lock
description: This skill should be used when the user asks about "read write lock pattern", "when to use read write lock", "shared exclusive lock", "concurrent reads", "reader writer problem", or mentions needing to allow multiple readers but exclusive writers.
version: 1.0.0
---

# Read-Write Lock Pattern

## What Is It
The Read-Write Lock pattern allows concurrent read access to a shared resource while ensuring exclusive access for writes. Multiple readers can read simultaneously, but writers need exclusive access, preventing reads during writes.

## When to Use
- **Caching systems** - Many reads, occasional updates
- **Configuration data** - Frequent reads, rare writes
- **Database access** - Concurrent queries, serializable updates
- **File systems** - Multiple readers, exclusive writers
- **In-memory stores** - High read-to-write ratio scenarios

## When NOT to Use
- **Write-heavy workloads** - Writers block everything
- **Simple synchronization** - Regular mutex is simpler
- **No read concurrency** - No benefit over simple lock
- **Real-time systems** - Writer starvation possible

## How to Implement

### Implementation Steps
1. Track number of active readers and waiting writers
2. Allow multiple readers when no writers active or waiting
3. Block readers when writer is active or waiting
4. Give writers exclusive access one at a time
5. Implement fairness to prevent starvation

### TypeScript Implementation

```typescript
class ReadWriteLock {
  private readers = 0;
  private writers = 0;
  private writeWaiters = 0;

  async readLock(): Promise<void> {
    while (this.writers > 0 || this.writeWaiters > 0) {
      await new Promise(r => setTimeout(r, 10));
    }
    this.readers++;
  }

  async readUnlock(): Promise<void> {
    this.readers--;
  }

  async writeLock(): Promise<void> {
    this.writeWaiters++;
    while (this.readers > 0 || this.writers > 0) {
      await new Promise(r => setTimeout(r, 10));
    }
    this.writeWaiters--;
    this.writers++;
  }

  async writeUnlock(): Promise<void> {
    this.writers--;
  }
}
```

## Code Examples
See `examples/` directory for runnable TypeScript implementations:
- `examples/read-write-lock.ts` - Basic implementation with shared resource
- `examples/read-write-lock-advanced.ts` - Real-world example with cache

## Related Patterns
- **Thread Pool** - Often used together for concurrent access
- **Proxy** - Protection proxy can use read-write locks
- **Observer** - Cache invalidation on writes
