C++:添加将在 std::future 完成时执行的回调
C++ : Add a callback that will be executed when an std::future is done
在python中你可以使用:
future.add_done_callback(f)
f
将在有结果或被取消时将 future 作为输入参数调用。
我如何在 C++ 中做类似的事情?
std::future
有 wait
方法,这是阻塞的。在后台线程中调用此方法,当 wait
returns 时,未来已准备就绪,然后您可以将就绪的未来作为参数调用您的回调:
一些代码:
struct FutureCallback {
std::thread th;
template<class C>
FutureCallback(C c, std::future<int> f) {
th = std::thread(
[c = std::move(c), f = std::move(f)]() mutable
{
f.wait(); // wait until future is ready
c(f); // call callback
}
);
}
~FutureCallback() {
if (th.joinable())
th.join();
}
};
void callback(std::future<int>& f) {
std::cout << "res printing in callback: " << f.get();
}
int main() {
std::packaged_task<int()> task([](){
std::this_thread::sleep_for(std::chrono::seconds(5));
return 10;
});
std::future<int> f = task.get_future();
FutureCallback cb(&callback,std::move(f));
task();
在python中你可以使用:
future.add_done_callback(f)
f
将在有结果或被取消时将 future 作为输入参数调用。
我如何在 C++ 中做类似的事情?
std::future
有 wait
方法,这是阻塞的。在后台线程中调用此方法,当 wait
returns 时,未来已准备就绪,然后您可以将就绪的未来作为参数调用您的回调:
一些代码:
struct FutureCallback {
std::thread th;
template<class C>
FutureCallback(C c, std::future<int> f) {
th = std::thread(
[c = std::move(c), f = std::move(f)]() mutable
{
f.wait(); // wait until future is ready
c(f); // call callback
}
);
}
~FutureCallback() {
if (th.joinable())
th.join();
}
};
void callback(std::future<int>& f) {
std::cout << "res printing in callback: " << f.get();
}
int main() {
std::packaged_task<int()> task([](){
std::this_thread::sleep_for(std::chrono::seconds(5));
return 10;
});
std::future<int> f = task.get_future();
FutureCallback cb(&callback,std::move(f));
task();