Skip to content

Latest commit

 

History

History
99 lines (61 loc) · 1.33 KB

04-locking.md

File metadata and controls

99 lines (61 loc) · 1.33 KB

04 - Locking and Atomic Operations

Goal

Learn different ways to protect shared state.

Implementations

Create:

  • LockCounter
  • MonitorCounter
  • InterlockedCounter
  • optional ReaderWriterLockCounter

Step 1: lock

Use a private lock object.

private readonly object _sync = new();

Never expose the lock object publicly.

Step 2: Monitor

Rewrite the same logic using:

Monitor.Enter(_sync);
Monitor.Exit(_sync);

Use try/finally.

Step 3: Interlocked

Use:

Interlocked.Increment(ref _value);

Use this for simple atomic numeric operations.

Step 4: ReaderWriterLockSlim

Use this only to explore read-heavy scenarios.

Tests

For every implementation:

  • single increment
  • many increments
  • concurrent increments

Benchmarks

Measure:

  • 1,000 increments
  • 100,000 increments
  • 1,000,000 increments
  • concurrent increments

Trade-offs

lock

Pros:

  • Simple.
  • Protects complex invariants.
  • Easy to understand.

Cons:

  • Can block.
  • Can cause deadlocks.
  • Can suffer under high contention.

Interlocked

Pros:

  • Very fast for simple operations.
  • No explicit lock object.
  • Low overhead.

Cons:

  • Hard to compose.
  • Not suitable for complex state transitions.

Key takeaway

Use the simplest synchronization primitive that correctly protects the invariant.