c++
std::packaged_task
Exception propagation through threads.
std::packaged_task wraps any callable target so that it can be invoked asynchronously. Its return value or exception thrown is stored in a shared state which can be accessed through std::future objects.
![]() |
Note |
|---|---|
cppreference: |
A task (std::packaged_task object) can be invoked asynchronously by threads.
#include <iostream> #include <thread> #include <future> int main() { // Template: return_type(arg_type) std::packaged_task<void(void)> task{ [] { std::cout << "Hello, c++!" << std::endl; } }; std::jthread thread{std::move(task)}; thread.join(); }
future.get() does not have to be called in this example, because the thread will invoke and run the task.
To get return value or exception thrown, the future object has to be used.
#include <iostream> #include <thread> #include <future> using std::string_literals::operator""s; int main(int argc, char ** argv) { std::packaged_task<int(void)> task{ [&] { std::cout << "Hello, c++!" << std::endl; if (argc >=3 && "true"s == argv[2]) throw std::runtime_error{"Test Exception"}; return 1333; } }; std::future<int> future = task.get_future(); std::jthread thread{std::move(task)}; thread.join(); if (argc >= 2 && "true"s == argv[1]) { try { int result = future.get(); std::cout << "Result: " << result << std::endl; } catch (const std::exception & e) { std::cout << "OK: " << e.what() << std::endl; } } }
$ b2 -q -j3 $ ./bin/gcc-15/debug/cxxstd-26-iso/edir Hello, c++! $ ./bin/gcc-15/debug/cxxstd-26-iso/edir true Hello, c++! Result: 1333 $ ./bin/gcc-15/debug/cxxstd-26-iso/edir true true Hello, c++! OK: Test Exception
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
Tue Jun 23 05:52:05 AM UTC 2026
//////////////////////////////////////////////////////////////////////
+
Github:
https://github.com/cppfx/cpphtgt
+
Powered by:
B2 Build
| boost quickbook
+
+