On this page
  1. Tutorial: jthread Work Queue & Atomics
  2. Goal
  3. Compile & Run
  4. Complete Pure-STL Example
  5. Key Takeaways

Tutorial: jthread Work Queue & Atomics

Prev: Ranges & Span Data Pipeline | Up: tutorials | Next: third_party
Rel: std::jthread, std::mutex & std::scoped_lock, std::atomic
Ref: cppreference — std::jthread | cppreference — std::condition_variable_any
Tags: #public #prog #cpp #tutorial #concurrency #tier/core


Goal

Build a minimal, leak-free concurrent work queue using C++20 std::jthread, std::condition_variable_any (which wakes automatically on std::stop_token cancellation), std::mutex, and std::atomic.

Compile & Run

clang++ -std=c++20 -O2 -Wall -Wextra -pthread jthread_queue.cpp -o jthread_queue && ./jthread_queue

Complete Pure-STL Example

#include <atomic>
#include <condition_variable>
#include <deque>
#include <iostream>
#include <mutex>
#include <stop_token>
#include <thread>
#include <vector>

int main() {
    std::mutex mu;
    std::condition_variable_any cv;
    std::deque<int> queue;
    std::atomic<int> sum{0};

    auto worker_fn = [&](std::stop_token st) {
        while (true) {
            int job = 0;
            {
                std::unique_lock lock(mu);
                // Wakes on non-empty queue OR stop_token cancellation
                cv.wait(lock, st, [&] { return !queue.empty(); });
                if (queue.empty()) {
                    return; // stop requested and queue drained
                }
                job = queue.front();
                queue.pop_front();
            }
            sum.fetch_add(job * job, std::memory_order_relaxed);
        }
    };

    {
        std::vector<std::jthread> workers;
        for (int i = 0; i < 4; ++i) {
            workers.emplace_back(worker_fn);
        }

        for (int i = 1; i <= 10; ++i) {
            {
                std::scoped_lock lock(mu);
                queue.push_back(i);
            }
            cv.notify_one();
        }
        // Wait briefly for queue to drain or rely on explicit shutdown signal
        std::this_thread::sleep_for(std::chrono::milliseconds(50));
    } // Leaving scope calls request_stop() + join() on every jthread

    std::cout << "Sum of squares (1..10) = " << sum.load() << '\n'; // 385
    return 0;
}

Key Takeaways

Linked from

Related notes