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
- Race condition demonstration (unsafe counter)
- Spinlock protection
- Mutex protection
- Atomic operations (lock-free)
- Multiple kernel threads for concurrency testing
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
- Atomic: Simple increment/decrement (no lock needed!)
- Spinlock: Fast operations, interrupt context
- Mutex: Longer operations, can sleep
3. Performance Trade-offs
- Atomic > Spinlock > Mutex (in terms of overhead)
- But all are correct, unlike the unsafe version
Try It Yourself
Modify the code to:
- Increase
ITERATIONSto see more race conditions - Add delays in critical sections
- Try different numbers of threads
- Test with
CONFIG_DEBUG_SPINLOCKenabled