Multithreading in C++
Course objectives
After completing this course you will be able to:
- create, join and end threads
- synchronize access to shared resources (mutexes, conditional variables, atomic variables, etc.)
- catch and avoid bugs such as race condition, deadlock, etc.
- create multithread-safe data structures (thread-safe queue) and use them to implement the Producer-Consumer pattern
- implement Thread Pool and Active Object design patterns
Course syllabus
Introduction to multithreading
- Threads and processes
- Basics concepts of concurrency: program correctness, race-condition, mutual exclusion, liveness, starvation of threads, deadlock
Thread management
- Classes:
std::thread&std::jthread - Creating and running tasks in separate threads
- Joining and detaching threads
- Grouping threads – storing threads in standard containers
- Hardware concurrency
- Handling exceptions in threads -
std::exception_ptr
Synchronizing threads - mutexes
- Lockable concepts
- Mutexes – implementation in standard library
std::mutex,std::timed_mutexandstd::shared_mutex- Recursive mutexes
- Lock managers –
std::lock_guard<Mutex>andstd::unique_lock<Mutex>classes - Synchronizing multithreaded code using mutexes
- Avoiding deadlocks – using
std::lock()function - Shared mutexes & locks – implementation of readers-writers pattern
Event synchronization
- Communication mechanisms between threads
- Busy waits – atomic flags
- Idle waits – condition variables -
std::condition_variableclass
- Thread-safe implementation of a queue
- Producer-Consumer Design Pattern
Lazy initialization
• Thread-safe lazy initialization – Singleton and Virtual Proxy
Introduction to atomic types
std::atomic<T>class- Acquire-Release semantics
- Memory model in C++11
- Introduction to lock-free algorithms and data structures
Asynchronous functions
- Asynchronous function calls –
std::async() - Running asynchronous tasks –
std::packaged_taskclass - Futures – results of asynchronous functions
std::promise- communication between threads
Design Patterns in multithreading
- Thread Pool
- Active Object
Prerequisites
Attendance of our Programming in C++ course or equivalent experience with C++