C++ Async & Futures Quiz
40 in-depth questions covering C++ async programming with std::async, std::future, std::promise, task-based concurrency, and custom thread pool patterns — with 16 code examples to solidify understanding.
Question 1
What is std::async in C++?
Question 2
What is the difference between std::launch::async and std::launch::deferred?
auto future1 = std::async(std::launch::async, expensive_function);
// Runs immediately in new thread
auto future2 = std::async(std::launch::deferred, expensive_function);
// Defers execution until future.get() is called
future1.get(); // May block if not ready
future2.get(); // Executes synchronously hereQuestion 3
What is std::future and how does it work?
#include <future>
auto future = std::async(std::launch::async, []() {
std::this_thread::sleep_for(std::chrono::seconds(1));
return 42;
});
// Do other work...
int result = future.get(); // Blocks until result is readyQuestion 4
What is the difference between future.get() and future.wait()?
std::future<int> future = std::async(expensive_calculation);
// wait() - just waits, doesn't get result
future.wait(); // Blocks until computation finishes
// future is still valid, can call get() later
// get() - waits and retrieves result
int result = future.get(); // Blocks and gets result
// future is now invalid, cannot use againQuestion 5
What is std::promise and how does it relate to std::future?
#include <future>
std::promise<int> promise;
std::future<int> future = promise.get_future();
void producer() {
int result = compute_value();
promise.set_value(result); // Fulfill promise
}
void consumer() {
int value = future.get(); // Get fulfilled value
}Question 6
What is future.wait_for() and when would you use it?
std::future<int> future = std::async(long_running_task);
auto status = future.wait_for(std::chrono::milliseconds(100));
if (status == std::future_status::ready) {
int result = future.get(); // Result is ready
} else if (status == std::future_status::timeout) {
// Timeout occurred, do something else
continue_processing();
} else {
// Future was deferred
}Question 7
What is task-based concurrency?
Question 8
What is the difference between std::async with default launch policy and explicit std::launch::async?
// Default policy (implementation defined)
auto f1 = std::async(compute);
// Explicit async
auto f2 = std::async(std::launch::async, compute);
// Explicit deferred
auto f3 = std::async(std::launch::deferred, compute);
// Both policies
auto f4 = std::async(std::launch::async | std::launch::deferred, compute);Question 9
What is future chaining or continuation?
auto future1 = std::async([]() { return 42; });
auto future2 = std::async([f = std::move(future1)]() mutable {
int value = f.get(); // Get first result
return value * 2; // Process it
});
// Or using then() concept (not in standard yet)
// auto future3 = future1.then([](int x) { return x * 2; });Question 10
What is the purpose of std::shared_future?
#include <future>
std::promise<int> promise;
std::shared_future<int> shared_future = promise.get_future();
// Multiple consumers can access the same result
std::future<int> future1 = shared_future;
std::future<int> future2 = shared_future;
promise.set_value(42);
int result1 = future1.get(); // OK
int result2 = future2.get(); // Also OK - shared_future allows multiple getsQuestion 11
What is a thread pool and why use it with async programming?
class ThreadPool {
std::vector<std::thread> workers;
std::queue<std::function<void()>> tasks;
std::mutex queue_mutex;
std::condition_variable cv;
bool stop = false;
public:
template<class F> void enqueue(F&& f) {
std::unique_lock<std::mutex> lock(queue_mutex);
tasks.emplace(std::forward<F>(f));
cv.notify_one();
}
~ThreadPool() {
stop = true;
cv.notify_all();
for (auto& worker : workers) worker.join();
}
};Question 12
What is the difference between packaged_task and promise?
std::packaged_task<int()> task([]() { return 42; });
std::future<int> future = task.get_future();
std::thread t(std::move(task)); // Execute in thread
t.join();
int result = future.get(); // Get result
// vs promise:
std::promise<int> promise;
std::future<int> future2 = promise.get_future();
promise.set_value(42); // Manual fulfillmentQuestion 13
What is async exception handling?
auto future = std::async([]() {
try {
risky_operation();
return 42;
} catch (const std::exception& e) {
throw; // Exception propagates to future
}
});
try {
int result = future.get(); // May throw
} catch (const std::exception& e) {
handle_error(e);
}Question 14
What is work stealing in thread pools?
Question 15
What is the difference between fire-and-forget tasks and result-returning tasks?
// Fire-and-forget: no result needed
std::async(std::launch::async, []() {
log_message("Background task");
// No return value
});
// Result-returning: need the result
auto future = std::async(std::launch::async, []() {
return compute_expensive_result();
});
int result = future.get(); // Wait for resultQuestion 16
What is async cleanup and resource management?
class AsyncResource {
std::future<void> cleanup_future;
public:
AsyncResource() {
// Start async cleanup of previous instance
cleanup_future = std::async(std::launch::async, []() {
cleanup_old_resources();
});
}
~AsyncResource() {
if (cleanup_future.valid()) {
cleanup_future.wait(); // Ensure cleanup completes
}
}
};Question 17
What is the difference between synchronous and asynchronous programming models?
Question 18
What is future unwrapping or nested futures?
auto nested_future = std::async([]() {
// Return another future
return std::async(std::launch::async, []() {
return 42;
});
});
// Without unwrapping: future<future<int>>
// With unwrapping (conceptual): future<int>
// Manual unwrapping:
auto outer_future = nested_future;
auto inner_future = outer_future.get(); // Get the inner future
int result = inner_future.get(); // Get the final resultQuestion 19
What is async cancellation and how is it implemented?
Question 20
What is the difference between std::async and std::thread for async programming?
auto future = std::async(std::launch::async, func, arg1, arg2);
// Higher-level: manages thread, provides future, exception handling
std::thread t(func, arg1, arg2);
t.join(); // Lower-level: manual thread management, no built-in result handlingQuestion 21
What is async composition or combining multiple futures?
auto f1 = std::async([]() { return 10; });
auto f2 = std::async([]() { return 20; });
// Manual composition
auto combined = std::async([f1 = std::move(f1), f2 = std::move(f2)]() mutable {
return f1.get() + f2.get(); // Wait for both and combine
});
int result = combined.get(); // 30Question 22
What is the purpose of std::future_status?
Question 23
What is async deadlock and how to avoid it?
// Potential deadlock
std::mutex mtx;
auto future = std::async(std::launch::async, [&]() {
std::lock_guard<std::mutex> lock(mtx);
return compute();
});
// In same thread:
std::lock_guard<std::mutex> lock(mtx); // Deadlock!
int result = future.get(); // Waits for async function that needs same lockQuestion 24
What is the difference between eager and lazy async execution?
Question 25
What is async result caching or memoization?
std::map<int, std::future<int>> cache;
std::future<int> get_cached_result(int key) {
auto it = cache.find(key);
if (it != cache.end()) {
return it->second; // Return cached future
}
// Start async computation
auto future = std::async(std::launch::async, [key]() {
return expensive_compute(key);
});
cache[key] = future; // Cache the future
return future;
}Question 26
What is the difference between promise.set_value() and promise.set_exception()?
std::promise<int> promise;
std::future<int> future = promise.get_future();
// Normal completion
promise.set_value(42);
// Exception occurred
try {
risky_operation();
promise.set_value(42);
} catch (const std::exception& e) {
promise.set_exception(std::current_exception()); // Store exception
}
// Consumer sees the exception
try {
int result = future.get(); // Throws stored exception
} catch (const std::exception& e) {
handle_error(e);
}Question 27
What is async fan-out and fan-in pattern?
// Fan-out: start multiple async operations
auto f1 = std::async([]() { return process_data(data1); });
auto f2 = std::async([]() { return process_data(data2); });
auto f3 = std::async([]() { return process_data(data3); });
// Fan-in: combine results
auto combined = std::async([f1 = std::move(f1), f2 = std::move(f2), f3 = std::move(f3)]() mutable {
return combine_results(f1.get(), f2.get(), f3.get());
});Question 28
What is the purpose of std::launch::deferred policy?
Question 29
What is async barrier or synchronization point?
std::vector<std::future<void>> futures;
// Start multiple async operations
for (auto& data : dataset) {
futures.push_back(std::async(std::launch::async,
[data]() { process_item(data); }));
}
// Barrier: wait for all to complete
for (auto& future : futures) {
future.wait(); // Or future.get() if result needed
}
// All operations completed, continue with next phaseQuestion 30
What is the difference between std::async and thread pool enqueue?
// std::async - creates thread per call (potentially)
auto f1 = std::async(func);
// Thread pool - reuses threads
thread_pool.enqueue(func); // No future returned
// Thread pool with future
std::promise<void> promise;
auto future = promise.get_future();
thread_pool.enqueue([promise = std::move(promise)]() mutable {
func();
promise.set_value(); // Signal completion
});Question 31
What is async timeout handling?
auto future = std::async(expensive_operation);
auto status = future.wait_for(std::chrono::seconds(5));
if (status == std::future_status::ready) {
return future.get(); // Success
} else {
// Timeout - cancel or handle differently
throw std::runtime_error("Operation timed out");
// Or: return default value, or retry
}Question 32
What is the difference between shared_future and regular future?
Question 33
What is async batching or request coalescing?
class BatchProcessor {
std::vector<Request> pending_requests;
std::mutex mutex;
std::condition_variable cv;
void process_batch() {
std::vector<Request> batch;
{
std::unique_lock<std::mutex> lock(mutex);
cv.wait(lock, [this]{ return pending_requests.size() >= BATCH_SIZE; });
batch = std::move(pending_requests);
pending_requests.clear();
}
// Process entire batch efficiently
process_batch_efficiently(batch);
}
};Question 34
What is the purpose of packaged_task?
Question 35
What is async pipeline or dataflow programming?
auto stage1_future = std::async([]() { return read_data(); });
auto stage2_future = std::async([f1 = std::move(stage1_future)]() mutable {
auto data = f1.get(); // Get stage 1 result
return process_data(data); // Stage 2 processing
});
auto stage3_future = std::async([f2 = std::move(stage2_future)]() mutable {
auto processed = f2.get(); // Get stage 2 result
return save_result(processed); // Stage 3 saving
});Question 36
What is the difference between async and deferred futures?
Question 37
What is async load balancing?
class LoadBalancer {
std::vector<std::shared_ptr<ThreadPool>> pools;
std::atomic<size_t> next_pool = 0;
std::future<void> submit_task(std::function<void()> task) {
size_t pool_index = next_pool.fetch_add(1) % pools.size();
return pools[pool_index]->enqueue_with_future(task);
}
};Question 38
What is the difference between future.valid() and future.wait_for()?
std::future<int> future;
if (future.valid()) {
// Future contains async operation
auto status = future.wait_for(std::chrono::seconds(1));
if (status == std::future_status::ready) {
int result = future.get();
}
} else {
// Future is empty/default constructed
}Question 39
What is async circuit breaker pattern?
class CircuitBreaker {
std::atomic<int> failure_count = 0;
std::atomic<bool> open = false;
std::future<Result> call_async(std::function<Result()> func) {
if (open.load()) {
return std::async([]() {
return Result::failure("Circuit open");
});
}
return std::async([this, func = std::move(func)]() {
try {
auto result = func();
failure_count = 0; // Reset on success
return result;
} catch (...) {
failure_count++;
if (failure_count > THRESHOLD) {
open = true; // Open circuit
}
throw;
}
});
}
};Question 40
What are the fundamental principles for effective async programming in C++?
