Threads: std::thread & std::jthread
Starting a thread (<thread>)
void work(int id) { ... }
std::thread t(work, 1); // starts running immediately
t.join(); // wait for it to finish
Lambdas work too: std::thread t([] { ... });
join or detach — you must choose ⚠️
join(): wait for the thread to finishdetach(): let it run independently (rarely a good idea — it may outlive the data it uses)- Destroying a
std::threadthat's still joinable calls std::terminate
std::jthread (C++20) ✅
- Joins automatically in its destructor (RAII)
- Supports cooperative cancellation with
std::stop_token:
std::jthread worker([](std::stop_token st) {
while (!st.stop_requested()) { /* work */ }
});
worker.request_stop();
Passing arguments
Arguments are copied into the thread. To pass by reference, wrap with std::ref(x) — and make sure x lives long enough.
Useful functions
std::thread::hardware_concurrency() (number of hardware threads), std::this_thread::sleep_for(100ms), std::this_thread::get_id()
Splitting work ✅
Divide data into chunks, give each thread its own chunk and its own result slot, join, then combine. No shared writes → no locks needed.
Concurrency vs parallelism
- Concurrency: dealing with many things at once (UI + network)
- Parallelism: doing work simultaneously to finish faster (summing a big array on 8 cores)
Dangers (next lesson)
Two threads writing the same variable without synchronization = data race = undefined behaviour. Output from several threads interleaves unpredictably.
Example
#include <chrono>
#include <iostream>
#include <numeric>
#include <thread>
#include <vector>
void sum_range(const std::vector<long long>& data, std::size_t begin, std::size_t end, long long& result) {
result = std::accumulate(data.begin() + static_cast<long>(begin), data.begin() + static_cast<long>(end), 0LL);
}
int main() {
std::vector<long long> data(1'000'000);
std::iota(data.begin(), data.end(), 1); // 1 .. 1,000,000
const std::size_t parts = 4;
std::vector<long long> partial(parts, 0); // one result slot per thread: no sharing
std::vector<std::thread> threads;
std::size_t chunk = data.size() / parts;
for (std::size_t i = 0; i < parts; ++i) {
std::size_t b = i * chunk, e = (i == parts - 1) ? data.size() : b + chunk;
threads.emplace_back(sum_range, std::cref(data), b, e, std::ref(partial[i]));
}
for (auto& t : threads) t.join(); // wait for all of them
for (std::size_t i = 0; i < parts; ++i) std::cout << "part " << i << ": " << partial[i] << '\n';
long long total = std::accumulate(partial.begin(), partial.end(), 0LL);
std::cout << "total: " << total << " (formula: " << 1'000'000LL * 1'000'001 / 2 << ")\n";
{
std::jthread auto_joined([] { std::this_thread::sleep_for(std::chrono::milliseconds(20)); });
} // joins automatically here
std::cout << "jthread joined automatically\n";
int ticks = 0;
{
std::jthread worker([&ticks](std::stop_token st) {
while (!st.stop_requested()) {
++ticks;
std::this_thread::sleep_for(std::chrono::milliseconds(5));
}
});
std::this_thread::sleep_for(std::chrono::milliseconds(50));
worker.request_stop(); // cooperative cancellation
}
std::cout << "worker stopped after some ticks: " << (ticks > 0 ? "yes" : "no") << '\n';
std::cout << "hardware threads available: " << (std::thread::hardware_concurrency() > 0 ? "at least 1" : "unknown") << '\n';
return 0;
}
/* Output:
part 0: 31250125000
part 1: 93750125000
part 2: 156250125000
part 3: 218750125000
total: 500000500000 (formula: 500000500000)
jthread joined automatically
worker stopped after some ticks: yes
hardware threads available: at least 1
*/