driver-know-hows

device driver related stuff

View on GitHub

Locking and Synchronization Demo

Description

Demonstrates race conditions and various synchronization mechanisms in the kernel. Shows why locking is needed and how to use different lock types.

Features

Build & Test

make
sudo insmod lock_demo.ko

# Watch detailed output showing race conditions
dmesg | tail -50

sudo rmmod lock_demo

Expected Output

=== Locking Demo: Starting ===
Expected count: 4000 (4 threads × 1000 iterations)

--- Test 1: Unsafe counter (expect wrong result) ---
Thread 0-3: Starting/Finishing unsafe operations...
Result: unsafe_counter = 3842 (expected 4000)
  ⚠ RACE CONDITION DETECTED! Lost updates!

--- Test 2: Spinlock protected (expect correct result) ---
Thread 0-3: Starting/Finishing spinlock operations...
Result: spinlock_counter = 4000 (expected 4000)
  ✓ CORRECT! Spinlock prevented race conditions

--- Test 3: Mutex protected (expect correct result) ---
Thread 0-3: Starting/Finishing mutex operations...
Result: mutex_counter = 4000 (expected 4000)
  ✓ CORRECT! Mutex prevented race conditions

--- Test 4: Atomic operations (expect correct result) ---
Thread 0-3: Starting/Finishing atomic operations...
Result: atomic_counter = 4000 (expected 4000)
  ✓ CORRECT! Atomic operations are lock-free!

=== Locking Demo: Complete ===

Lock Types Compared

Type Context Can Sleep Performance Use Case
None Any N/A Fastest UNSAFE - Race conditions!
Atomic Any No Fastest Simple counters/flags
Spinlock Any No Fast Short critical sections
Mutex Process Yes Slower Long critical sections

Learning Points

1. Race Conditions are Real

The unsafe counter will almost always show lost updates, demonstrating why synchronization is critical.

2. When to Use Each Lock

3. Performance Trade-offs

Try It Yourself

Modify the code to: