Thuta Learning
C++
AdvancedProgrammingBeginner

Concurrency with std::jthread

C++Lesson 2935 min

What you'll walk away with

  • Create std::jthread objects and explain why, unlike std::thread, they join automatically in their destructor
  • Describe what a data race is and choose between not sharing, std::atomic and std::mutex to prevent it
  • Read results only after the threads have joined, so the program prints the same output on every run
  • Stop a worker loop cooperatively with std::stop_token and request_stop()

Explain it simply

Concurrency in plain language

Most computers today have several cores, yet an ordinary program uses only one. A thread is another path of execution running at the same time inside the same program. Split the job of analysing a thousand files into four parts, hand them to four threads, and four cores can work at once.

Think of four cooks in one kitchen: as long as each works on their own chopping board, everything is fine. Trouble starts when two of them season the same pot at the same moment. Most of concurrency is about protecting that shared pot.

Problem → Why → Solution

The problem: a counter that changes every run

Four threads each increment a shared counter 100000 times, so the result should be 400000. Five runs on one machine printed 236686, 162324, 146455, 159018 and 169839: five different numbers, none of them right. Tested with a single thread, it is always correct.

racy_counter.cpp
#include <iostream>
#include <thread>
#include <vector>

int main() {
    int counter = 0;                             // shared, unprotected
    {
        std::vector<std::jthread> threads;
        for (int t = 0; t < 4; ++t) {
            threads.emplace_back([&counter] {
                for (int i = 0; i < 100000; ++i) ++counter;   // data race
            });
        }
    }
    std::cout << "counter: " << counter << '\n';  // expected 400000
}

Why updates get lost

++counter is not one step: it reads the value, adds one and writes it back. If two threads both read 41 and both write 42, one increment is lost. C++ calls this a data race: two threads touch the same memory location without synchronization and at least one of them writes. The result is undefined behaviour, so a wrong number is the best case.

Core concept: thread lifetime and protecting shared data

All threads in a process share the same memory: globals, the heap and anything captured by reference. That sharing is both the power and the danger. An std::thread must be joined or detached before it is destroyed; otherwise its destructor calls std::terminate and the program ends abruptly. C++20's std::jthread (in <thread>) requests a stop and then joins in its destructor, so a scope { std::vector<std::jthread> ... } becomes a natural 'wait for everyone' point.

There are three cures for a data race. The best is not sharing at all: each thread works on its own slot or copy, and the results are combined after the join. For a single value such as a counter or a flag, use std::atomic, which turns ++ into one indivisible step. For multi-step updates, such as pushing into a vector, use std::mutex with std::lock_guard, which locks in its constructor and unlocks in its destructor.

TechniqueUse it forCost
One slot per threadsplit work combined at the endalmost none
std::atomic<T>a single counter or flagsmall
std::mutex + std::lock_guardmulti-step updates, containersthreads wait in line

std::stop_token provides cooperative cancellation. If the callable's first parameter is an std::stop_token, jthread passes one in. request_stop() only sets a flag; the thread must check stop_requested() regularly and leave on its own. There is no standard way to kill a thread forcibly.

The last point is output: when several threads write to std::cout, each << is a separate call, so lines get mixed together. Collect results and let main print them after the join. If you only need whole lines, C++20's std::osyncstream (<syncstream>) keeps each line intact, but the order of lines can still change from run to run.

Give every thread its own chopping board
  1. Split the work: one part per thread
  2. Each thread writes only its own slot
  3. Shared values: atomic or mutex
  4. Scope ends = join; then read results

Never read a result before the join; the closing brace of the jthread scope is that boundary.

General pattern

cpp
std::vector<Result> slots(workers);              // one slot per thread
{
    std::vector<std::jthread> threads;
    for (int w = 0; w < workers; ++w) {
        threads.emplace_back([&, w] { slots[w] = compute(w); });
    }
}                                                // all threads joined here

std::jthread worker([](std::stop_token token) {
    while (!token.stop_requested()) { /* one unit of work */ }
});
worker.request_stop();                           // ask; the thread decides when

Give each thread its index by value and let it write only its own slot; the jthreads join when the block ends. A long-running worker takes a stop token and checks it on every pass of its loop.

Worked example: summing with four threads

The numbers 1 to 1000 are summed by four threads. Each thread writes only its own slot of the partial vector, so no lock is needed; the count of finished threads is shared, so it is an std::atomic. The order in which the threads run differs from run to run, but the output is always the same, because main prints only after the join.

parallel_sum.cpp
#include <atomic>
#include <iostream>
#include <numeric>
#include <thread>
#include <vector>

int main() {
    std::vector<int> data(1000);
    std::iota(data.begin(), data.end(), 1);          // 1, 2, ..., 1000

    const int workers = 4;
    const std::size_t chunk = data.size() / workers;
    std::vector<long long> partial(workers, 0);      // one slot per thread
    std::atomic<int> finished{0};

    {
        std::vector<std::jthread> threads;
        for (int w = 0; w < workers; ++w) {
            threads.emplace_back([&, w] {            // copy w, share the rest
                auto first = data.begin() + w * chunk;
                auto last = (w == workers - 1) ? data.end() : first + chunk;
                partial[w] = std::accumulate(first, last, 0LL);
                ++finished;                          // atomic: safe from any thread
            });
        }
    }   // each jthread joins here, so all partial sums are written

    for (int w = 0; w < workers; ++w) {
        std::cout << "worker " << w << ": " << partial[w] << '\n';
    }
    long long total = std::accumulate(partial.begin(), partial.end(), 0LL);
    std::cout << "finished: " << finished << '\n';
    std::cout << "total: " << total << '\n';
}

Code breakdown

  1. One slot per threadstd::vector<long long> partial(workers, 0);

    All four elements exist before any thread starts, so the vector itself never changes while they run; writing to different elements is not a data race.

  2. Capture w by valuethreads.emplace_back([&, w] {

    & shares data, partial and finished by reference, while w is copied. Capturing w by reference would make every thread share the one variable the loop keeps changing.

  3. Write only your own slotpartial[w] = std::accumulate(first, last, 0LL);

    Each thread sums its own chunk and writes only partial[w]. The 0LL makes the sum accumulate in long long.

  4. An atomic shared counter++finished;

    finished is an std::atomic<int>, so all four threads can increment it at once without losing an update. A plain int would bring back the race from the problem section.

  5. The join point} // each jthread joins here, so all partial sums are written

    When the threads vector is destroyed, each jthread's destructor joins. Reading partial after this brace is both safe and correct.

You should see
worker 0: 31375
worker 1: 93875
worker 2: 156375
worker 3: 218875
finished: 4
total: 500500
How the threads fork and join
  1. main prepares the data and four partial slots
  2. Four jthreads start, each summing its own chunk
  3. Threads run in parallel and write their own slot
  4. The scope ends and every jthread joins
  5. main reads the partial sums and prints them

Stopping a worker politely

A background watcher polls every five milliseconds until a stop is requested. main waits a moment, calls request_stop() and joins. How many times the loop ran depends on the scheduler, so the program never prints that number, only facts that are the same on every run.

stop_token.cpp
#include <atomic>
#include <chrono>
#include <iostream>
#include <stop_token>
#include <thread>

int main() {
    std::atomic<int> polls{0};
    std::atomic<bool> cleanedUp{false};

    std::jthread watcher([&](std::stop_token token) {
        while (!token.stop_requested()) {        // cooperative: the thread checks
            ++polls;
            std::this_thread::sleep_for(std::chrono::milliseconds(5));
        }
        cleanedUp = true;                        // runs after the loop exits
    });

    std::this_thread::sleep_for(std::chrono::milliseconds(30));
    watcher.request_stop();                      // ask, do not kill
    watcher.join();                              // wait until it has finished

    std::cout << std::boolalpha;
    std::cout << "stop requested: " << watcher.get_stop_token().stop_requested() << '\n';
    std::cout << "cleaned up: " << cleanedUp << '\n';
    std::cout << "joinable after join: " << watcher.joinable() << '\n';
}

The output is stop requested: true, cleaned up: true and joinable after join: false. Setting cleanedUp after the loop shows that the thread gets to clean up on its own terms: close files, save finished work. Because join() was called explicitly, the destructor has nothing left to join.

A mutex for a shared container

Four threads increment a shared counter and also add to a shared log vector. ++counter is a single step, but push_back changes size, capacity and elements, which no atomic can protect; that needs a mutex.

mutex_log.cpp
#include <iostream>
#include <mutex>
#include <string>
#include <thread>
#include <vector>

int main() {
    std::vector<std::string> log;
    std::mutex logMutex;
    int counter = 0;                             // protected by logMutex too

    {
        std::vector<std::jthread> threads;
        for (int id = 0; id < 4; ++id) {
            threads.emplace_back([&, id] {
                for (int i = 0; i < 10000; ++i) {
                    std::lock_guard<std::mutex> lock(logMutex);   // unlocks at }
                    ++counter;
                }
                std::lock_guard<std::mutex> lock(logMutex);
                log.push_back("thread " + std::to_string(id) + " done");
            });
        }
    }

    std::cout << "counter: " << counter << '\n';
    std::cout << "log entries: " << log.size() << '\n';
}

This prints counter: 40000 and log entries: 4 on every run. The order of entries inside log can vary, which is why it is not printed. Keep a mutex next to the data it protects, and hold the lock for the shortest time that works.

In real projects

Threads in real projects

Threads show up daily in places like these, and most of them reuse the same three basic patterns: split and combine, protect shared state, stop politely:

  • Desktop and mobile apps keep the UI thread responsive by running heavy work such as file imports or image processing on a background thread, and stop it with a stop token when the window closes.
  • Servers handle requests in parallel on a thread pool and protect shared data such as caches and statistics with a mutex or atomics.
  • Data processing splits log files, images or simulations into chunks; each thread computes its own result and they are combined at the end, exactly like this lesson's example.
  • Game engines run audio, physics and asset loading on separate threads and exchange data at fixed synchronization points every frame.

Common mistakes

Common mistakes with threads

Forgetting to join an std::thread

If std::thread worker(task); reaches the end of its scope without join or detach, its destructor calls std::terminate. On this lesson's toolchain the program simply crashes without a message, and other platforms print different text. Use std::jthread, whose destructor joins for you.

Capturing the loop variable by reference

Writing [&] { slots[w] = ...; } makes every thread share the single w that the loop keeps incrementing, and w itself is destroyed when the loop ends. Threads write the wrong slot, or worse, undefined behaviour follows. Copy the index with [&, w].

Reading results before the join

Printing partial inside the jthread scope reads it while threads may still be writing, which is a data race in itself; sometimes you will see zeros. Move the reads after the scope's closing brace.

Writing to std::cout from every thread

When threads write std::cout << "worker " << w << ..., other threads can cut in between each <<, so lines get mixed and every run looks different. Collect results in slots and print them from main.

Mini challenge

Mini challenge: counting primes with four threads

Count the prime numbers from 1 to 20000 with four std::jthread workers, one range each. Each thread writes its range's prime count into its own slot and adds the numbers it checked to a shared atomic counter. Print the per-range results and the total only after the threads have joined.

  • Write isPrime(int) with simple trial division
  • Each thread writes only its own index of std::vector<int> primesPerPart(4)
  • Sum the count of checked numbers in an std::atomic<int>
  • Print nothing from inside the threads; the output must be identical on every run
parallel_primes.cpp
#include <atomic>
#include <iostream>
#include <thread>
#include <vector>

bool isPrime(int n) {
    // TODO: false below 2; otherwise try divisors d while d * d <= n
    return false;
}

int main() {
    const int limit = 20000;
    const int parts = 4;

    // TODO: a slot vector for the per-range counts and an atomic "checked" counter

    {
        // TODO: start one std::jthread per range; capture the range index by value
        // TODO: each thread counts primes in its range and writes only its slot
    }   // TODO: make sure nothing is read before this brace

    // TODO: print each range's count, then "checked N numbers, M primes"
}

Expected: It prints numbers 1-5000: 669 primes, 5001-10000: 560, 10001-15000: 525 and 15001-20000: 508, then checked 20000 numbers, 2262 primes, identically on every run.

Show hint

Range p runs from p * step + 1 to (p + 1) * step, with step = limit / parts. Write the lambda as [&, p], count into a local variable first and write the slot once at the end.

Show solution
parallel_primes.cpp
#include <atomic>
#include <iostream>
#include <thread>
#include <vector>

bool isPrime(int n) {
    if (n < 2) return false;
    for (int d = 2; d * d <= n; ++d) {
        if (n % d == 0) return false;
    }
    return true;
}

int main() {
    const int limit = 20000;
    const int parts = 4;
    const int step = limit / parts;              // 5000 numbers per thread

    std::vector<int> primesPerPart(parts, 0);    // each thread owns one slot
    std::atomic<int> checked{0};                 // shared counter, atomic

    {
        std::vector<std::jthread> threads;
        for (int p = 0; p < parts; ++p) {
            threads.emplace_back([&, p] {
                int from = p * step + 1;
                int to = (p + 1) * step;
                int found = 0;
                for (int n = from; n <= to; ++n) {
                    if (isPrime(n)) ++found;
                }
                primesPerPart[p] = found;        // write only our own slot
                checked += to - from + 1;
            });
        }
    }   // all four threads have joined here

    int total = 0;
    for (int p = 0; p < parts; ++p) {
        std::cout << "numbers " << p * step + 1 << "-" << (p + 1) * step
                  << ": " << primesPerPart[p] << " primes\n";
        total += primesPerPart[p];
    }
    std::cout << "checked " << checked << " numbers, " << total << " primes\n";
}

Quick quiz 1 / 3

What happens when main ends while std::thread t(work); was never joined or detached?

Quick quiz 2 / 3

Four threads each run ++counter 100000 times on a plain int shared by reference. What can the program print?

Quick quiz 3 / 3

Which lambda makes std::jthread pass in a stop token?

What to remember

  • std::jthread requests a stop and joins in its destructor, so the closing brace of its scope is a 'wait for everyone' point.
  • Two threads touching one memory location without synchronization, at least one writing, is a data race and undefined behaviour.
  • Prefer not sharing (one slot per thread); use std::atomic for a single value and std::mutex for multi-step updates.
  • std::stop_token is cooperative: request_stop() only asks, and the thread checks stop_requested() and leaves on its own.
  • Printing from main after the threads have joined keeps the output identical on every run.

C++ Multithreading Reference — cppreference

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.