← Back to C++ Course | Chapter 17: Advanced C++ | Lesson 14 of 17

C++ async & future

What is std::async?

The 'std::async' function template is used to run a task asynchronously, potentially in a new thread. It returns a 'std::future' object, which will hold the task's return value when it completes.

Example: What is std::async?

cpp
#include <iostream>
#include <future>

int compute() { return 42; }

int main() {
	std::future<int> result = std::async(compute); // runs, potentially on a new thread
	std::cout << result.get() << std::endl;
	return 0;
}

Working with std::future

A 'std::future' acts as a placeholder for a value that is being calculated. Calling get() on a future blocks your program and waits for the calculation to finish. You can only call get() once on any future object.

Example: Working with std::future

cpp
#include <iostream>
#include <future>

int compute() { return 100; }

int main() {
	std::future<int> f = std::async(compute);
	std::cout << f.get() << std::endl; // blocks until the value is ready
	return 0;
}

Launch Policies

You can control how std::async runs by passing a launch policy. 'std::launch::async' forces the task to run on a new thread immediately. 'std::launch::deferred' delays the task until you call get() or wait().

Example: Launch Policies

cpp
#include <iostream>
#include <future>

int compute() { return 5; }

int main() {
	auto f = std::async(std::launch::async, compute); // forces a new thread immediately
	std::cout << f.get() << std::endl;
	return 0;
}

std::promise and std::future

A 'std::promise' is used to send values to a 'std::future' running in another thread. The promise is the input end of the communication channel, and the future is the output end.

Example: std::promise and std::future

cpp
#include <iostream>
#include <future>
#include <thread>

void setValue(std::promise<int> p) {
	p.set_value(7); // sends the value to the paired future
}

int main() {
	std::promise<int> p;
	std::future<int> f = p.get_future();
	std::thread t(setValue, std::move(p));
	std::cout << f.get() << std::endl;
	t.join();
	return 0;
}

Waiting on Multiple Futures

You can use wait_for() to wait for an asynchronous task to finish, up to a specified timeout limit. This prevents your program from blocking indefinitely if a task hangs.

Example: Waiting on Multiple Futures

cpp
#include <iostream>
#include <future>
#include <chrono>

int compute() { return 1; }

int main() {
	auto f = std::async(compute);
	if (f.wait_for(std::chrono::seconds(1)) == std::future_status::ready) { // avoids blocking forever
		std::cout << f.get() << std::endl;
	}
	return 0;
}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.