C++ Programming

Concurrency and Multithreading

Master C++ programming from basics to advanced. Learn object-oriented programming, STL, memory management, and build high-performance applications.

On this page

Concurrency and Multithreading

Concurrency allows programs to execute multiple operations simultaneously, improving performance and responsiveness. Modern C++ (C++11+) provides excellent support for multithreading.

What is Concurrency?

Concurrency is the ability of a program to execute multiple tasks simultaneously. In C++11+, this is achieved through:

  • Threads: Separate execution paths
  • Mutexes: Synchronization primitives
  • Condition Variables: Thread coordination
  • Futures/Promises: Asynchronous operations

Creating Threads

Basic Thread Creation

1#include <thread>
2#include <iostream>
3using namespace std;
4 
5void threadFunction() {
6    cout << "Thread is running" << endl;
7}
8 
9int main() {
10    thread t(threadFunction);  // Create thread
11    t.join();  // Wait for thread to finish
12    return 0;
13}

Sample Output

Thread is running

Thread with Arguments

1void printMessage(const string& msg, int count) {
2    for (int i = 0; i < count; i++) {
3        cout << msg << " " << i << endl;
4    }
5}
6 
7int main() {
8    thread t(printMessage, "Hello", 5);
9    t.join();
10    return 0;
11}

Lambda Threads

1thread t([]() {
2    cout << "Lambda thread" << endl;
3});
4t.join();

Sample Output

Lambda thread

Thread Management

join() vs detach()

1thread t(function);
2 
3t.join();   // Wait for thread to complete
4// OR
5t.detach(); // Let thread run independently (daemon)

Important: Must call either join() or detach() before thread object is destroyed!

Race Conditions

Multiple threads accessing shared data without synchronization causes race conditions:

1int counter = 0;
2 
3void increment() {
4    for (int i = 0; i < 100000; i++) {
5        counter++;  // Race condition!
6    }
7}
8 
9int main() {
10    thread t1(increment);
11    thread t2(increment);
12    t1.join();
13    t2.join();
14    cout << counter << endl;  // May not be 200000!
15}

Mutex (Mutual Exclusion)

Mutex ensures only one thread accesses shared data at a time.

Basic Mutex

1#include <mutex>
2 
3mutex mtx;
4int counter = 0;
5 
6void increment() {
7    for (int i = 0; i < 100000; i++) {
8        mtx.lock();
9        counter++;
10        mtx.unlock();
11    }
12}

lock_guard (RAII)

1void increment() {
2    for (int i = 0; i < 100000; i++) {
3        lock_guard<mutex> lock(mtx);  // Automatic unlock
4        counter++;
5    }
6}

unique_lock

1unique_lock<mutex> lock(mtx);
2// Can unlock manually
3lock.unlock();
4// Can lock again
5lock.lock();

Types of Mutexes

std::mutex

Basic mutex (non-recursive).

std::recursive_mutex

Allows same thread to lock multiple times.

std::timed_mutex

Mutex with timeout support.

1timed_mutex mtx;
2if (mtx.try_lock_for(chrono::seconds(1))) {
3    // Lock acquired
4    mtx.unlock();
5}

Condition Variables

Allow threads to wait for conditions:

1#include <condition_variable>
2 
3condition_variable cv;
4mutex mtx;
5bool ready = false;
6 
7void worker() {
8    unique_lock<mutex> lock(mtx);
9    cv.wait(lock, []{ return ready; });  // Wait for condition
10    // Do work
11}
12 
13void producer() {
14    {
15        lock_guard<mutex> lock(mtx);
16        ready = true;
17    }
18    cv.notify_one();  // Notify waiting thread
19}

Atomic Operations

Atomic operations are thread-safe without mutexes:

1#include <atomic>
2 
3atomic<int> counter(0);
4 
5void increment() {
6    for (int i = 0; i < 100000; i++) {
7        counter++;  // Thread-safe!
8    }
9}

Benefits:

  • No mutex overhead
  • Lock-free operations
  • Better performance for simple operations

Futures and Promises

std::future

Represents a value that will be available in the future:

1#include <future>
2 
3int compute() {
4    return 42;
5}
6 
7int main() {
8    future<int> f = async(compute);
9    int result = f.get();  // Wait for result
10    return 0;
11}

std::promise

Set value from one thread, get from another:

1promise<int> p;
2future<int> f = p.get_future();
3 
4thread t([&p]() {
5    p.set_value(42);
6});
7 
8int result = f.get();  // Wait for value
9t.join();

std::async

Execute function asynchronously:

1auto future = async(launch::async, compute);
2int result = future.get();

Thread Safety

Thread-Safe Guidelines

  1. ✅ Use mutexes for shared mutable data
  2. ✅ Use atomic for simple operations
  3. ✅ Avoid shared state when possible
  4. ✅ Use lock_guard for automatic unlocking
  5. ✅ Minimize lock scope (lock late, unlock early)
  6. ✅ Avoid deadlocks (lock in consistent order)
  7. ✅ Use condition variables for coordination
  8. ✅ Prefer immutable data structures

Common Patterns

Pattern 1: Producer-Consumer

1queue<int> dataQueue;
2mutex mtx;
3condition_variable cv;
4 
5void producer() {
6    for (int i = 0; i < 10; i++) {
7        {
8            lock_guard<mutex> lock(mtx);
9            dataQueue.push(i);
10        }
11        cv.notify_one();
12    }
13}
14 
15void consumer() {
16    while (true) {
17        unique_lock<mutex> lock(mtx);
18        cv.wait(lock, []{ return !dataQueue.empty(); });
19        int value = dataQueue.front();
20        dataQueue.pop();
21        lock.unlock();
22        // Process value
23    }
24}

Pattern 2: Thread Pool

1// Use thread pool library or implement
2// Executes tasks in parallel

Deadlocks

Deadlock occurs when threads wait for each other indefinitely.

Avoiding Deadlocks

  1. Lock in consistent order
  2. Use timeout locks
  3. Avoid nested locks
  4. Use lock_guard (automatic unlock)

Best Practices

  1. ✅ Minimize shared state
  2. ✅ Use RAII for locks (lock_guard)
  3. ✅ Prefer atomic for simple operations
  4. ✅ Use condition variables for coordination
  5. ✅ Avoid data races
  6. ✅ Test thoroughly (race conditions are hard to debug)
  7. ✅ Use thread-safe containers when available
  8. ✅ Document thread safety guarantees

Common Mistakes

  • ❌ Forgetting to join() or detach() threads
  • ❌ Data races (unsynchronized access)
  • ❌ Deadlocks (circular waiting)
  • ❌ Using non-thread-safe functions
  • ❌ Holding locks too long
  • ❌ Not handling exceptions in threads
  • ❌ Race conditions in initialization

Next Steps

You've completed the C++ course! Continue learning:

  • Advanced Templates: Template metaprogramming
  • Design Patterns: Reusable solutions
  • C++20 Features: Concepts, coroutines, ranges
  • Performance Optimization: Profiling, optimization techniques
  • System Programming: OS APIs, low-level programming

Congratulations on mastering C++! 🎉

Hands-on Examples

Basic Threads

#include <iostream>
#include <thread>
#include <vector>
using namespace std;

void printMessage(const string& msg, int id) {
    for (int i = 0; i < 3; i++) {
        cout << "Thread " << id << ": " << msg << " " << i << endl;
        this_thread::sleep_for(chrono::milliseconds(100));
    }
}

void workerFunction(int id) {
    cout << "Worker " << id << " started" << endl;
    this_thread::sleep_for(chrono::milliseconds(500));
    cout << "Worker " << id << " finished" << endl;
}

int main() {
    cout << "=== Basic Thread Creation ===" << endl;
    
    // Create thread with function
    thread t1(printMessage, "Hello", 1);
    thread t2(printMessage, "World", 2);
    
    // Wait for threads to complete
    t1.join();
    t2.join();
    
    cout << "\n=== Multiple Threads ===" << endl;
    vector<thread> threads;
    
    // Create multiple threads
    for (int i = 0; i < 5; i++) {
        threads.emplace_back(workerFunction, i);
    }
    
    // Wait for all threads
    for (auto& t : threads) {
        t.join();
    }
    
    cout << "\n=== Lambda Thread ===" << endl;
    thread lambdaThread([]() {
        cout << "Lambda thread executing" << endl;
        this_thread::sleep_for(chrono::milliseconds(200));
        cout << "Lambda thread done" << endl;
    });
    
    lambdaThread.join();
    
    cout << "\nAll threads completed!" << endl;
    return 0;
}

Basic thread creation uses std::thread. Pass function and arguments to constructor. Must call join() to wait for completion or detach() to run independently. Threads execute concurrently. Use this_thread::sleep_for() for delays. Always join() or detach() before thread object is destroyed.

Sample Output

=== Basic Thread Creation ===
Thread 1: Hello 0
Thread 2: World 0
Thread 1: Hello 1
Thread 2: World 1
Thread 1: Hello 2
Thread 2: World 2

=== Multiple Threads ===
Worker 0 started
Worker 1 started
Worker 2 started
Worker 3 started
Worker 4 started
Worker 0 finished
Worker 1 finished
Worker 2 finished
Worker 3 finished
Worker 4 finished

=== Lambda Thread ===
Lambda thread executing
Lambda thread done

All threads completed!