PrevUpHomeNext

c++ std::packaged_task for exception propagation


> Start
> Synopsis
> Example: invoke by thread
> Example: use std::future
> Conclusion
> Back: Home

c++

std::packaged_task

Exception propagation through threads.

Synopsis

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] Note

cppreference:
The class template std::packaged_task wraps any Callable target (function, lambda expression, bind expression, or another function object) 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.

c++ Example: Invoke by thread

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.

c++ Example: use std::future

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;
		}
	}
}

Run

$ 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

Conclusion

//////////////////////////////////////////////////////////////////////

Home

//////////////////////////////////////////////////////////////////////

Tue Jun 23 05:52:05 AM UTC 2026

//////////////////////////////////////////////////////////////////////

Helpful

Jfty

Wtgo

Role

+

Github:
https://github.com/cppfx/cpphtgt

+

Powered by:
B2 Build | boost quickbook

+

Donate

+

@cppfx.xyz


















PrevUpHomeNext