Chapter 19: Multithreading & Concurrency

Multithreading & Concurrency in C++: Running Multiple Tasks at the Same Time!

Hello my fantastic student! 🌟 Welcome to Lesson 19 β€” Multithreading & Concurrency β€” one of the most powerful, most exciting, and also most dangerous topics in modern C++!

In today’s world, almost every serious application (games, servers, data processing, AI training, video editing…) uses multiple threads to do many things at the same time and make the best use of multi-core CPUs.

C++ gives us excellent tools starting from C++11 to write safe, efficient multi-threaded code.

Today we’ll cover everything in great detail:

  • std::thread – creating and managing threads
  • Mutex + lock_guard & unique_lock – protecting shared data
  • std::future, std::promise, std::async – getting results from threads
  • Atomics – lock-free programming for simple types

We’ll go very slowly, with real-life analogies, tons of examples, common mistakes, and modern best practices (2026 style).

Let’s start!

1. std::thread – Creating Independent Threads

Include: #include <thread>

Basic example – two threads running in parallel

C++

Important methods:

  • join() β†’ wait for thread to finish (most common)
  • detach() β†’ let thread run independently (dangerous β€” no control)
  • joinable() β†’ check if thread can be joined
  • std::this_thread::sleep_for() β†’ pause current thread

Passing arguments to thread:

C++

Modern best practice: Use lambda to capture variables safely:

C++

2. Mutex – Protecting Shared Data (Avoiding Data Races)

Problem: Multiple threads accessing same variable β†’ data race β†’ undefined behavior

Solution: std::mutex + locking

Include: #include <mutex>

Classic example – Bank account with concurrent deposits

C++

Two popular RAII locks:

Lock Type When to use Features
std::lock_guard Simple, automatic lock/unlock Cannot unlock manually
std::unique_lock More flexible (can unlock manually, moveable) Can defer lock, try_lock, timed lock

Example with unique_lock:

C++

3. std::future, std::promise, std::async – Getting Results from Threads

std::future β†’ a handle to a value that will be available in the future std::promise β†’ the other end β€” you set the value std::async β†’ easiest way to run a function asynchronously

Simple example with std::async:

C++

Using std::promise (more control):

C++

4. Atomics – Lock-Free Operations for Simple Types

std::atomic<T> – thread-safe operations without mutex

Include: #include <atomic>

Example – Safe counter without mutex

C++

Common atomic operations:

  • load(), store()
  • fetch_add(), fetch_sub()
  • compare_exchange_strong() (CAS – very powerful)

When to use atomics:

  • Simple counters, flags
  • Lock-free data structures

Summary Table – Quick Reference

Feature Best Use Case Key Class / Function
Creating threads Run independent tasks std::thread
Protect shared data Avoid data races std::mutex + lock_guard / unique_lock
Get result from thread Async computation std::future + std::async
Lock-free simple operations Counters, flags std::atomic

Your Mini Homework (Try These!)

  1. Create two threads that print numbers 1 to 10, but synchronized so they print alternately.
  2. Write a thread-safe queue using std::mutex and std::condition_variable (advanced bonus).
  3. Use std::async to compute factorial of a large number in background.
  4. Make a global std::atomic<bool> ready flag and have one thread set it after work.

You’re doing absolutely phenomenal! You’ve just mastered modern multithreading in C++ β€” this is the level needed for game engines, web servers, scientific computing, and almost every high-performance application.

Next lesson: File I/O, Streams & Serialization β€” reading/writing files, binary data, JSON/XML β€” super useful for real apps!

Any questions? Confused about lock_guard vs unique_lock? Want more examples with atomics or futures? Just ask β€” your friendly C++ teacher is right here for you! πŸš€

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *