Skip to content
binshelf/ cpp

Search lessons

Type a C++ term, like vector, reference, unique_ptr or use-after-free.

    Lessons

    On this page

    1. Key terms
    2. In 30 seconds
    3. Starting a thread and waiting for it
    4. Forgetting to join ends the program
    5. detach: letting go of a thread
    6. std::jthread: a thread that joins itself
    7. Asking a thread to stop
    8. Passing arguments to a thread
    9. Getting a result back
    10. How many threads?
    11. Two threads, one variable: a data race
    12. Which one should I use?
    13. Under the hood
    14. Common pitfalls
    15. A thread that outlives the variable it refers to
    16. Try it yourself

    Module 10 · Concurrency

    10.1Threads and jthread

    Run work on several threads at once with std::thread and std::jthread. Wait for them with join, stop them with a stop token, pass arguments and get results back, and see your first data race caught by ThreadSanitizer.

    About 25 minutesIntermediate

    On this page
    1. Key terms
    2. In 30 seconds
    3. Starting a thread and waiting for it
    4. Forgetting to join ends the program
    5. detach: letting go of a thread
    6. std::jthread: a thread that joins itself
    7. Asking a thread to stop
    8. Passing arguments to a thread
    9. Getting a result back
    10. How many threads?
    11. Two threads, one variable: a data race
    12. Which one should I use?
    13. Under the hood
    14. Common pitfalls
    15. A thread that outlives the variable it refers to
    16. Try it yourself

    Key terms

    thread
    One path of execution through your program. A program starts with one thread, the one running main; it can start more, and they all share the program's memory.
    std::thread
    A standard type from <thread> that starts a function on a new thread. Before it's destroyed, you must either join it or detach it.
    join and detach
    t.join() waits until thread t has finished. t.detach() lets it run on its own, and you can never wait for it.
    std::jthread
    A thread that joins itself when it's destroyed, and that you can ask to stop (C++20).
    std::stop_token
    What a std::jthread hands its function so the function can check stop_requested() and finish early.
    std::future
    A result that isn't ready yet. get() waits for it. std::async runs a function and gives you its result as a future.
    data race
    Two threads use the same memory at the same time, at least one of them writes, and nothing makes them take turns. It is undefined behavior.
    ThreadSanitizer
    A sanitizer that finds data races while the program runs. Turn it on with -fsanitize=thread; it can't be combined with AddressSanitizer.

    Your computer has several cores, each able to run instructions on its own, but a C++ program starts with only one thread: the one that runs main. Everything you’ve written so far does one step at a time on one core. To count GC in a million DNA reads faster, or to keep a program responsive while it works, you start more threads and let them run at the same time.

    In 30 seconds

    • std::thread t(f); runs f on a new thread. t.join() waits for it to finish. A std::thread that’s destroyed without join or detach ends the program.
    • std::jthread joins itself in its destructor, and it can pass its function a std::stop_token so you can ask it to stop.
    • Arguments are copied into the thread. Give each thread its own slot to write its result, or use std::async and a std::future.
    • Two threads that touch the same variable, with at least one writing, are a data race: undefined behavior. ThreadSanitizer finds it.

    Starting a thread and waiting for it

    Give std::thread a function, and it starts running that function on a new thread right away. The thread that created it keeps going. join() makes the caller wait until the new thread has finished:

    #include <print>
    #include <string_view>
    #include <thread>
    
    int count_gc(std::string_view dna) {
        int count = 0;
        for (char base : dna) {
            count += base == 'G' || base == 'C';
        }
        return count;
    }
    
    int main() {
        int first = 0;
        int second = 0;
        std::thread a([&first] { first = count_gc("GATTACA"); });
        std::thread b([&second] { second = count_gc("GGCCGCAT"); });
        a.join();
        b.join();
        std::println("{} {}", first, second);
    }

    Output

    2 6

    The two counts may run at the same time on two cores, or one after the other; the system decides. What’s certain is that after both join calls, both threads are done and first and second hold their results. That’s why main prints only after joining. Each thread writes its own variable, so the two never touch the same memory. A lambda is the usual way to give a thread its work; [&first] lets it change a local variable, as in Lambdas.

    Forgetting to join ends the program

    A std::thread that still has a running (or finished but unjoined) thread when it’s destroyed doesn’t wait and doesn’t guess. Its destructor calls std::terminate, which ends the program on the spot:

    #include <thread>
    
    int main() {
        std::thread worker([] {});
    } // worker is destroyed here without join()

    This fails when it runs

    terminate called without an active exception

    GCC’s library prints “terminate called without an active exception” (the same std::terminate that an uncaught exception leads to) and the program aborts. The fix is a worker.join(); before the end of the scope, on every path out of it, including when an exception is thrown in between. That’s hard to get right by hand, which is why std::jthread exists.

    detach: letting go of a thread

    detach() is the other way to satisfy the destructor: the thread keeps running on its own, and the std::thread object no longer refers to it. You can never wait for it again. When main returns, the program ends and a detached thread is stopped wherever it happens to be:

    #include <chrono>
    #include <print>
    #include <thread>
    
    std::thread logger([] {
        std::this_thread::sleep_for(std::chrono::seconds(1));
        std::println("never printed");
    });
    logger.detach();
    std::println("main returns without waiting");

    Output

    main returns without waiting

    std::this_thread::sleep_for pauses the current thread for a duration from <chrono>. The detached thread was still asleep when main returned, so its line never appeared. Worse, a detached thread that uses a local variable can outlive it. Avoid detach: join every thread you start.

    std::jthread: a thread that joins itself

    std::jthread (C++20, also in <thread>) works like std::thread, but its destructor joins. It follows RAII: the object owns the thread, and destroying the object waits for the thread. A vector of jthreads and a block around it give you “start them all, then wait for them all”:

    #include <print>
    #include <string_view>
    #include <thread>
    #include <vector>
    
    int count_gc(std::string_view dna) {
        int count = 0;
        for (char base : dna) {
            count += base == 'G' || base == 'C';
        }
        return count;
    }
    
    int main() {
        std::vector<std::string_view> reads = {"GATTACA", "GGCCGCAT", "ATATAT"};
        std::vector<int> gc(reads.size());
        {
            std::vector<std::jthread> workers;
            for (std::size_t i = 0; i < reads.size(); ++i) {
                workers.emplace_back(
                    [&reads, &gc, i] { gc[i] = count_gc(reads[i]); });
            }
        } // each jthread joins here
        std::println("{}", gc);
    }

    Output

    [2, 6, 0]

    Each thread gets its own index i, captured by value, and writes only gc[i]. The threads share the vector, but never an element of it. You can still call join() on a jthread yourself when you need the result before the end of the scope.

    Asking a thread to stop

    Some threads loop until there’s no more work, or until someone tells them to quit. If a jthread’s function takes a std::stop_token as its first parameter, the jthread passes one in. The function checks stop_requested() from time to time; another thread calls request_stop() on the jthread:

    #include <chrono>
    #include <print>
    #include <stop_token>
    #include <thread>
    
    int main() {
        std::jthread worker([](std::stop_token stop) {
            while (!stop.stop_requested()) {
                std::this_thread::sleep_for(std::chrono::milliseconds(1));
            }
            std::println("worker: stop requested, finishing");
        });
        std::this_thread::sleep_for(std::chrono::milliseconds(20));
        worker.request_stop();
        worker.join();
        std::println("main: worker has finished");
    }

    Output

    worker: stop requested, finishing
    main: worker has finished

    The order of the two lines is fixed: the worker prints before it finishes, and main prints only after join. Stopping is a request, not a force: the thread decides when to look and how to finish cleanly. A jthread’s destructor calls request_stop() before it joins, so even without the last two calls this loop would end. A plain std::thread has no stop token; you’d need a flag of your own that both threads can use safely, such as the std::atomic<bool> from the next lesson.

    Passing arguments to a thread

    Instead of a lambda, you can pass the function and its arguments, as in std::jthread t(add_reads, total, 5);. The thread copies each argument into its own storage first, so it never refers to a caller’s variable that might be gone by the time it runs. That’s why a non-const reference parameter doesn’t compile: it would refer to the thread’s copy, and the change would be lost.

    #include <thread>
    
    void add_reads(int& total, int count) {
        total += count;
    }
    
    int main() {
        int total = 0;
        std::jthread worker(add_reads, total, 5);
    }

    The compiler rejects this

    In file included from main.cpp:1:
    /usr/include/c++/15/thread: In instantiation of ‘static std::thread std::jthread::_S_create(std::stop_source&, _Callable&&, _Args&& ...) [with _Callable = void (&)(int&, int); _Args = {int&, int}]’:
    /usr/include/c++/15/thread:167:28:   required from ‘std::jthread::jthread(_Callable&&, _Args&& ...) [with _Callable = void (&)(int&, int); _Args = {int&, int}; <template-parameter-1-3> = void]’
          |       : _M_thread{_S_create(_M_stop_source, std::forward<_Callable>(__f),
          |                   ~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
          |                             std::forward<_Args>(__args)...)}
          |                             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    main.cpp:9:44:   required from here
        9 |     std::jthread worker(add_reads, total, 5);
          |                                            ^
    /usr/include/c++/15/thread:274:27: error: static assertion failed: std::jthread arguments must be invocable after conversion to rvalues
          |             static_assert(is_invocable_v<decay_t<_Callable>,
          |                           ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
          |                                          decay_t<_Args>...>,
          |                                          ~~~~~~~~~~~~~~~~~~
    /usr/include/c++/15/thread:274:27: note: ‘std::is_invocable_v<void (*)(int&, int), int, int>’ evaluates to false

    GCC’s library catches this with a static_assert that reads “std::jthread arguments must be invocable after conversion to rvalues”: the copies are passed as temporaries, and an int& can’t bind to a temporary. When you do want the thread to use your variable, say so with std::ref from <functional>. It wraps a reference so it survives the copy:

    #include <functional>
    #include <print>
    #include <thread>
    
    void add_reads(int& total, int count) {
        total += count;
    }
    
    int main() {
        int total = 10;
        std::jthread worker(add_reads, std::ref(total), 5);
        worker.join();
        std::println("{}", total);
    }

    Output

    15

    std::cref does the same for a const reference. Either way, you’ve promised that total outlives the thread, and that no other thread touches it meanwhile. A lambda with an explicit capture list says the same thing more visibly, so most code uses lambdas.

    Getting a result back

    A thread’s function can return a value, but std::thread and std::jthread throw it away. The pattern above, one slot per thread in a vector created before the threads, is the most common way to collect results: each thread writes its own slot, and you read them after joining.

    For one-off tasks, std::async from <future> runs a function and gives you a std::future for its result. get() waits until the result is ready and returns it:

    #include <future>
    #include <print>
    #include <string_view>
    
    int count_gc(std::string_view dna) {
        int count = 0;
        for (char base : dna) {
            count += base == 'G' || base == 'C';
        }
        return count;
    }
    
    int main() {
        std::future<int> first =
            std::async(std::launch::async, count_gc, "GGCCGCAT");
        int second = count_gc("GATTACA"); // runs on main's thread meanwhile
        std::println("{} {}", first.get(), second);
    }

    Output

    6 2

    std::launch::async asks for a new thread. Without it, the library may instead run the function later, inside get(), on the calling thread. If the function throws, get() rethrows the exception in the caller. A future is a good fit for “start this, I’ll need the answer later”; for many threads working on parts of one job, the slots pattern is simpler. Parallel work splits a big job across threads.

    How many threads?

    std::thread::hardware_concurrency() returns how many threads the hardware can run at once: the number of cores, or twice that on cores that run two threads each. It’s a hint, and it returns 0 if the system can’t tell. The answer depends on the machine, so this output is from the machine that checked this page:

    #include <print>
    #include <thread>
    
    unsigned n = std::thread::hardware_concurrency();
    std::println("{} hardware threads", n);

    Output from one run (it varies)

    24 hardware threads

    You can start more threads than that; the system then takes turns running them. For work that keeps a core busy, more threads than hardware threads only adds switching.

    Two threads, one variable: a data race

    Everything so far kept threads apart: each wrote its own variable or slot. Here two threads add to the same total:

    #include <print>
    #include <thread>
    
    int main() {
        int total = 0;
        auto count = [&total] {
            for (int i = 0; i < 100'000; ++i) {
                ++total;
            }
        };
        std::thread a(count);
        std::thread b(count);
        a.join();
        b.join();
        std::println("{}", total);
    }

    This fails when it runs

    WARNING: ThreadSanitizer: data race
      Read of size 4 at 0x… by thread T2:
        #0 operator() main.cpp:8
           … 6 frames inside the standard library
    
      Previous write of size 4 at 0x… by thread T1:
        #0 operator() main.cpp:8
           … 6 frames inside the standard library
    
      Location is stack of main thread.
    
      Thread T2 (running) created by main thread at:
        #0 pthread_create
           … 1 frame inside the standard library
        #2 main main.cpp:12
    
      Thread T1 (running) created by main thread at:
        #0 pthread_create
           … 1 frame inside the standard library
        #2 main main.cpp:11
    
    SUMMARY: ThreadSanitizer: data race main.cpp:8 in operator()

    You might expect 200000. Built without a sanitizer, it can print less, and a different number each run. ++total isn’t one step: the processor loads total, adds 1, and stores it back. If both threads load the same value, both store that value plus one, and one of the additions is lost:

    StepThread aThread btotal in memory
    1loads 4141
    2loads 4141
    3stores 4242
    4stores 4242

    Lost updates are only the visible symptom. A data race is undefined behavior, and the optimizer is allowed to assume your program has none.

    This example ran with ThreadSanitizer (-fsanitize=thread), which watches every memory access while the program runs and reports each race it sees. Read its report from the top:

    • “WARNING: ThreadSanitizer: data race” names the bug.
    • The next two blocks are the two accesses that conflict: a read by thread T2 and an earlier write by thread T1, each with its stack. Both point at main.cpp:8, the ++total inside the lambda. operator() is how the report names a lambda’s body.
    • “Location is stack of main thread” says where the variable lives: total is a local in main.
    • “Thread T2 (running) created by main thread at” shows where each thread was started: main.cpp:12 and main.cpp:11, the two std::thread lines. When threads are started from inside library code, these stacks can stop in the standard library instead.

    ThreadSanitizer can’t be combined with AddressSanitizer, so build a separate copy of your program with it, g++ -std=c++23 -g -O1 -fsanitize=thread main.cpp, and run your tests with it. It finds races that happen in the run, so give it runs where the threads really overlap. The next lesson, Mutexes and atomics, shows the fixes: a mutex makes threads take turns, and std::atomic<int> makes ++total one indivisible step.

    Which one should I use?

    WhatWhenWhyHow
    std::jthreadAlmost always, when you start a thread yourself.Joins itself, even when an exception leaves the scope, and supports stopping.std::jthread t([&] { … });
    std::threadOlder code, or when you must not join automatically.Same as jthread without the safety; forgetting join ends the program.std::thread t(f); … t.join();
    std::async + std::futureOne task whose result you need later.The result, or its exception, comes back through get().auto f = std::async(std::launch::async, g, x);
    detach()Almost never.You can’t wait for the thread, and it can outlive what it uses.t.detach();

    Rule of thumb: use std::jthread, give each thread its own data to write, and read the results only after the threads are joined.

    Under the hood

    A thread is something the operating system runs. Each thread gets its own stack for its local variables and function calls, but all threads of a program share the heap, the global variables and everything else in memory. That’s why a worker can use main’s locals through a reference capture. The system’s scheduler decides which threads run on which cores and when. A thread can be paused at any instruction and resumed later, possibly on another core. That’s why output order and lost updates change between runs.

    The std::thread object itself is small. With GCC’s library it holds only the system’s handle for the thread; std::jthread adds a pointer to the shared stop state:

    #include <print>
    #include <thread>
    
    std::println("{} {}", sizeof(std::thread), sizeof(std::jthread));

    Output

    8 16

    Starting a thread costs far more than calling a function: the system has to create a stack and schedule the thread. Two threads doing a tiny job each can be slower than one thread doing both. Give each thread a large chunk of work, and reuse threads when you have many small tasks (a thread pool, described in Parallel work).

    Common pitfalls

    A thread that outlives the variable it refers to

    start_count starts a thread and returns it. The lambda captures scores by reference, but scores is a local variable of start_count and is destroyed when it returns. The thread is still running, and reads it afterwards:

    #include <chrono>
    #include <print>
    #include <thread>
    #include <vector>
    
    std::jthread start_count(int n) {
        std::vector<int> scores(n, 1);
        return std::jthread([&scores] {
            std::this_thread::sleep_for(std::chrono::milliseconds(20));
            std::println("{}", scores.size());
        });
    }
    
    int main() {
        std::jthread worker = start_count(3);
    }

    This fails when it runs

    ERROR: AddressSanitizer: stack-use-after-return on address 0x…
    READ of size 8 at 0x… thread T1
        #0 std::vector<int, std::allocator<int> >::size() const
        #1 operator() main.cpp:10
           … 6 frames inside the standard library
    
    Address 0x… is located in stack of thread T0 at offset 104 in frame
        #0 start_count(int) main.cpp:6
    
      This frame has 4 object(s):
        [32, 33) '<unknown>'
        [48, 52) '<unknown>'
        [64, 72) '<unknown>'
        [96, 120) 'scores' (line 7) <== Memory access at offset 104 is inside this variable
          (longjmp and C++ exceptions *are* supported)
    SUMMARY: AddressSanitizer: stack-use-after-return main.cpp:10 in operator()

    AddressSanitizer reports a stack-use-after-return: thread T1 read scores, which lived in start_count’s frame on the main thread’s stack (T0). This is the bug from Lambdas with a thread added, and timing makes it harder to catch: without the sleep, the thread might finish before start_count returns, and the bug would hide until some other run. Capture by value, [scores], so the thread owns its copy:

    #include <print>
    #include <thread>
    #include <vector>
    
    std::jthread start_count(int n) {
        std::vector<int> scores(n, 1);
        return std::jthread([scores] { std::println("{}", scores.size()); });
    }
    
    int main() {
        std::jthread worker = start_count(3);
    }

    Output

    3

    Common pitfallDeclare data before the threads that use it

    Local variables are destroyed in reverse order. A jthread declared after the vector it writes into is destroyed, and joined, first, while the vector still exists. Declared before it, the thread would still be running when the vector is destroyed.

    Try it yourself

    Try it yourself

    sum_range adds the numbers from first up to, but not including, last. Change main so that four std::jthreads each sum a quarter of the range 0 to 1,000,000, and main prints the total.

    #include <print>
    
    long sum_range(long first, long last) {
        long total = 0;
        for (long i = first; i < last; ++i) {
            total += i;
        }
        return total;
    }
    
    int main() {
        std::println("{}", sum_range(0, 1'000'000));
    }

    Expected output

    499999500000
    Show a hint

    Make a std::vector<long> with one slot per thread. Start the threads in a block, each with its own index captured by value, and sum the slots after the block ends.

    Show a solution
    #include <print>
    #include <thread>
    #include <vector>
    
    long sum_range(long first, long last) {
        long total = 0;
        for (long i = first; i < last; ++i) {
            total += i;
        }
        return total;
    }
    
    int main() {
        const long n = 1'000'000;
        const int threads = 4;
        std::vector<long> partial(threads);
        {
            std::vector<std::jthread> workers;
            for (int t = 0; t < threads; ++t) {
                long first = n / threads * t;
                long last = n / threads * (t + 1);
                workers.emplace_back([&partial, t, first, last] {
                    partial[t] = sum_range(first, last);
                });
            }
        }
        long total = 0;
        for (long p : partial) {
            total += p;
        }
        std::println("{}", total);
    }

    Each jthread writes only its own slot, so no two threads touch the same memory and there's no data race. The block makes the jthreads join before main reads the slots, and adding the slots in order gives the same total every run.

    Saved in this browser only.