4
我的假設是packaged_task
底下有promise
。如果我的任務拋出異常,我該如何將其路由到關聯的future
?只需promise
我可以撥打set_exception
- 我該怎麼做packaged_task
?是否有一個packaged_task :: set_exception等價物?
我的假設是packaged_task
底下有promise
。如果我的任務拋出異常,我該如何將其路由到關聯的future
?只需promise
我可以撥打set_exception
- 我該怎麼做packaged_task
?是否有一個packaged_task :: set_exception等價物?
一個std::packaged_task
有一個關聯的std::future
對象,它將保存異常(或任務的結果)。您可以通過撥打std::packaged_task
的get_future()
成員函數來檢索未來。
這意味着它足以讓throw
與打包任務關聯的函數內發生異常,以便任務未來捕獲該異常(並在未來對象上調用get()
時重新拋出異常)。
例如:
#include <thread>
#include <future>
#include <iostream>
int main()
{
std::packaged_task<void()> pt([]() {
std::cout << "Hello, ";
throw 42; // <== Just throw an exception...
});
// Retrieve the associated future...
auto f = pt.get_future();
// Start the task (here, in a separate thread)
std::thread t(std::move(pt));
try
{
// This will throw the exception originally thrown inside the
// packaged task's function...
f.get();
}
catch (int e)
{
// ...and here we have that exception
std::cout << e;
}
t.join();
}