Skip to content
KALANBLON
Show contents

Chapter 5 of 7 · 20 min

Threads, locks and asynchronous tasks

By the end of this chapter, you'll be able to

  • Start threads with std::thread and wait for them to finish with join
  • Explain what a data race is
  • Protect shared data with std::atomic or a std::mutex
  • Get the result of an asynchronous task with std::async and std::future

Starting threads

std::thread starts a function (often a lambda) in a new thread of execution, which runs at the same time as the rest of the program. join() waits for it to finish.

#include <atomic>
#include <future>
#include <iostream>
#include <mutex>
#include <numeric>
#include <thread>
#include <vector>

int main() {
    std::atomic<int> visits{0};
    std::vector<std::thread> threads;
    for (int i = 0; i < 4; ++i) {
        threads.emplace_back([&visits] {
            for (int k = 0; k < 10000; ++k) ++visits;   // atomic increment: nothing is lost
        });
    }
    for (auto& t : threads) t.join();
    std::cout << "visits: " << visits << '\n';

    std::mutex lock;
    std::vector<int> log;
    std::vector<std::thread> writers;
    for (int id = 1; id <= 3; ++id) {
        writers.emplace_back([&lock, &log, id] {
            std::lock_guard<std::mutex> guard(lock);    // only one thread at a time here
            log.push_back(id);
        });
    }
    for (auto& w : writers) w.join();
    std::cout << "entries: " << log.size() << '\n';

    std::vector<long> numbers(1'000'000);
    std::iota(numbers.begin(), numbers.end(), 1);
    auto middle = numbers.begin() + static_cast<long>(numbers.size() / 2);
    auto first_half = std::async(std::launch::async, [&numbers, middle] {
        return std::accumulate(numbers.begin(), middle, 0L);
    });
    long second_half = std::accumulate(middle, numbers.end(), 0L);
    std::cout << "sum: " << first_half.get() + second_half << '\n';
}
visits: 40000
entries: 3
sum: 500000500000
  • std::atomic<int>: its operations (++, read, write) are indivisible. Four threads increment 10,000 times each: you get exactly 40,000.
  • std::mutex (mutual exclusion lock) protects a whole block of code. std::lock_guard locks it when created and unlocks it when destroyed: that's RAII, the lock is released even if an exception happens.
  • std::async starts a task and returns a std::future. get() waits for the task to finish and gives its result. Here, the two halves of the sum are computed in parallel.
  • The order of the log's entries depends on the order the threads run in, which varies: we only display how many there are, which is guaranteed.

The data race

Without atomic or a lock, ++counter breaks down into three steps: read the value, add 1, write the result. If two threads read the same value before either of them writes, one increment is lost. That's a data race. In C++, it's undefined behaviour.

One increment is lost. With atomic or a mutex, reading and writing are indivisible.

Step 6 of 6
Text description of the animation
  1. Both threads want to add 1 to the same counter.
  2. A reads the value 5.
  3. Before A writes, B also reads 5.
  4. A computes 5 + 1 and writes 6.
  5. B also computes 5 + 1 and writes 6, overwriting A's work.
  6. One increment is lost. With atomic or a mutex, reading and writing are indivisible.

Your turn

Worked exercise

Worked exercise: splitting without sharing

Compute the sum of the squares of the integers from 1 to 4,000 by spreading the work over 4 threads. Each thread handles a slice of 1,000 numbers. To avoid any data race without a lock, each thread writes its result into its own slot of a vector, then the main thread adds up the four slots.

Hint 1
Thread number t (from 0 to 3) handles the numbers from t * 1000 + 1 to (t + 1) * 1000.
Hint 2
Capture t by copy in the lambda: the loop variable changes while the threads are running. The results vector, though, is captured by reference; each thread only writes into results[t].
Show the solution and common mistakes
#include <iostream>
#include <numeric>
#include <thread>
#include <vector>

int main() {
    const int nb_threads = 4;
    const long slice = 1000;
    std::vector<long> results(nb_threads, 0);
    std::vector<std::thread> threads;
    for (int t = 0; t < nb_threads; ++t) {
        threads.emplace_back([&results, t, slice] {
            long sum = 0;
            for (long n = t * slice + 1; n <= (t + 1) * slice; ++n) sum += n * n;
            results[static_cast<std::size_t>(t)] = sum;
        });
    }
    for (auto& th : threads) th.join();
    long total = std::accumulate(results.begin(), results.end(), 0L);
    std::cout << "sum of squares: " << total << '\n';
}
sum of squares: 21341334000

Each slot of the vector is written by only one thread, and only read after the join()s: there's no concurrent access, so no race. It's often the best strategy: share as little as possible.

Common mistakes:

  • Capturing t by reference ([&]): when the thread starts, the loop may already have incremented t, and two threads handle the same slice.
  • Adding into a single shared variable protected by a lock on every iteration: it's correct, but the threads spend their time waiting for each other, and the program becomes slower than with a single thread.

Summary

  1. 1std::thread starts a function in parallel; join waits for it to finish.
  2. 2Two threads changing the same data without protection create a data race.
  3. 3std::atomic makes an operation indivisible; std::mutex and lock_guard protect a block.
  4. 4std::async starts a task; get() on the future waits and gives its result.
  5. 5The best synchronisation is often to share nothing.

Your progress is saved on this device. Create a free account to keep your progress on all your devices.