Skip to main content
Be Bitwise
C++Concurrency in C++

std::thread and Futures

C++11 shipped a standard threading library that's friendlier and more portable than raw pthreads. Two abstractions carry most of the weight: std::thread for running work in parallel, and std::future/std::promise for shuttling results back.

Creating Threads

cpp
#include <iostream>
#include <thread>
void worker(int id) {
std::cout << "Thread " << id << " running\n";
}
int main() {
std::thread t1(worker, 1);
std::thread t2(worker, 2);
t1.join();
t2.join();
return 0;
}

Unlike pthreads, std::thread is a real C++ object with move semantics. The thread fires up the moment you construct it. Before the std::thread object goes out of scope, you'd better have called join() or detach() on it — otherwise the destructor pulls the rip cord with std::terminate.

Threads with Lambdas

Lambdas are the most common way to create threads in modern C++:

cpp
#include <iostream>
#include <thread>
#include <vector>
int main() {
std::vector<std::thread> threads;
for (int i = 0; i < 4; i++) {
threads.emplace_back([i]() {
std::cout << "Thread " << i << " working\n";
});
}
for (auto& t : threads) {
t.join();
}
return 0;
}
Key Concept

Capture by reference ([&]) in a thread lambda is a footgun if the referenced variable evaporates before the thread does. Prefer capture by value ([=]) or move ([x = std::move(data)]) for thread functions.

std::async and std::future

std::async launches a task and returns a std::future that holds the eventual result:

cpp
#include <iostream>
#include <future>
#include <numeric>
#include <vector>
long long sum_range(const std::vector<int>& v, size_t start, size_t end) {
long long sum = 0;
for (size_t i = start; i < end; i++) {
sum += v[i];
}
return sum;
}
int main() {
std::vector<int> data(1000000, 1);
size_t mid = data.size() / 2;
auto future1 = std::async(std::launch::async, sum_range,
std::cref(data), 0, mid);
auto future2 = std::async(std::launch::async, sum_range,
std::cref(data), mid, data.size());
long long total = future1.get() + future2.get();
std::cout << "Total: " << total << "\n";
return 0;
}

std::launch::async pins the task to a new thread. Leave it off and the implementation can defer execution until .get() is called.

Here's one to predict before you open the answer. The code runner on this site can't start threads, so this one stays on paper. Each task sleeps for a second, and neither future gets stored:

cpp
#include <chrono>
#include <future>
#include <iostream>
#include <thread>
void slow(int id) {
std::this_thread::sleep_for(std::chrono::seconds(1));
std::cout << "task " << id << " done\n";
}
int main() {
std::async(std::launch::async, slow, 1);
std::async(std::launch::async, slow, 2);
std::cout << "main done\n";
}
How long does it take, and in what order do the lines print?

About two seconds, and always task 1 done, task 2 done, main done. Each std::async call returns a temporary future that's destroyed at the end of its statement, and a future that came from std::async blocks in its destructor until the task has finished. The two "background" tasks run strictly one after the other. Store the futures in named variables if you want them to overlap.

std::promise

A std::promise is the writing end of a future. You create a promise, extract its future, then set the value from any thread:

cpp
#include <iostream>
#include <thread>
#include <future>
void compute(std::promise<int> promise) {
// Simulate work
int result = 42;
promise.set_value(result);
}
int main() {
std::promise<int> p;
std::future<int> f = p.get_future();
std::thread t(compute, std::move(p));
std::cout << "Result: " << f.get() << "\n";
t.join();
return 0;
}

Promises are move-only. You have to std::move them into the thread function.

What happens if compute() returns without ever calling set_value?

main doesn't hang. When a promise is destroyed with nothing stored, it stores a std::future_error with the code std::future_errc::broken_promise instead, so f.get() throws that exception on the main thread.

Exception Propagation

Futures have a great trick up their sleeve: exceptions propagate across thread boundaries automatically.

cpp
#include <iostream>
#include <future>
#include <stdexcept>
int risky_computation() {
throw std::runtime_error("Something went wrong");
return 42;
}
int main() {
auto future = std::async(std::launch::async, risky_computation);
try {
int result = future.get(); // Rethrows the exception
std::cout << result << "\n";
} catch (const std::exception& e) {
std::cerr << "Caught: " << e.what() << "\n";
}
return 0;
}

A thrown exception gets stashed inside the future. Call .get() and the exception comes back to life on the calling thread. Far cleaner than the C-flavoured pattern of plumbing error codes through every layer.

std::packaged_task

std::packaged_task wraps a callable and hands you a future for its return value. Handy when you're building task queues.

cpp
#include <iostream>
#include <future>
#include <functional>
#include <thread>
int main() {
std::packaged_task<int(int, int)> task([](int a, int b) {
return a + b;
});
std::future<int> result = task.get_future();
// Can be moved to another thread or queued
std::thread t(std::move(task), 3, 4);
t.join();
std::cout << "Result: " << result.get() << "\n";
return 0;
}

Thread Safety of Standard Library

The C++ standard provides these guarantees:

  • Const member functions of standard library types can be called concurrently from multiple threads
  • Different objects can be accessed concurrently, even of the same type
  • The same object cannot be modified from multiple threads without synchronisation
cpp
// SAFE: different objects
std::vector<int> v1, v2;
std::thread t1([&]{ v1.push_back(1); });
std::thread t2([&]{ v2.push_back(2); });
// UNSAFE: same object, concurrent modification
std::vector<int> v;
std::thread t1([&]{ v.push_back(1); });
std::thread t2([&]{ v.push_back(2); }); // Data race!

Hardware Concurrency

Query the number of hardware threads available:

cpp
unsigned int n = std::thread::hardware_concurrency();
std::cout << "Hardware threads: " << n << "\n";

Use it to size your thread pool. For CPU-bound work, going beyond the hardware count usually loses ground to context-switch overhead.

Jthread (C++20)

C++20 added std::jthread. It joins itself in the destructor and supports cooperative cancellation:

cpp
#include <chrono>
#include <thread>
#include <iostream>
int main() {
std::jthread t([](std::stop_token token) {
while (!token.stop_requested()) {
std::cout << "Working...\n";
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
std::cout << "Stopping gracefully\n";
});
std::this_thread::sleep_for(std::chrono::milliseconds(350));
t.request_stop();
// Automatically joins when t goes out of scope
return 0;
}

jthread knocks out the two threading bugs people write most often: forgetting to join (which trips std::terminate) and the lack of a clean way to ask a thread to stop.