A minimal C++ implementation of a fair mutex using a ticket lock mechanism β for educational purposes only.
This project demonstrates how to implement a basic mutual exclusion (mutex) mechanism in C++ from scratch. (version 0.1--SpinLock)
Inspired by the ticket lock algorithm, DomainLock ensures FIFO ordering: the first thread that tries to acquire the lock will be the first to hold it.
The lock uses two atomic counters:
ticket: tracks the next ticket to assign.serving: tracks the currently served ticket.
Each thread receives a unique ticket and waits until its number matches the serving counter.
- β Fair lock acquisition (FIFO)
- β
try_lock()andlock()support - β
Uses C++20
<atomic>for thread-safe primitives - β Logs thread activity (acquire/release)
- β Lightweight and dependency-free
β οΈ Not suitable for production use β built for educational purposes only
- C++20 compatible compiler (
g++,clang++)
[Thread 140184607512320] acquired lock (ticket 0)
[Thread 140184599119616] waiting for turn (ticket 1, serving 0)
[Thread 140184607512320] released the variable
[Thread 140184599119616] acquired lock (ticket 1)
...
Counter: 4
- SpinLock
- atomic
- memory_order
- C++ Concurrency in Action by Anthony Williams
- SpinLock simple atomic lock
- Fair lock and ticket logic
- Add
try_lock_for(timeout)method with time-based locking - Implement
DomainLockGuard(RAII wrapper likestd::lock_guard) - Implement the use of
condition_variables - Implement
unique_lock - Optional logging toggle to enable/disable thread logs
- Benchmark and compare with
std::mutexunder various loads - Add reentrant locking (like
recursive_mutex) - Experiment with condition variable support (
wait()/notify()interface) - Stress test with 100+ threads and measure fairness/starvation
- Add visuals (e.g., ticket lock flow diagram)
- Unit test :/
- Using logging library