我知道了原因future
从返回std::async
有一些特殊的共享状态wait on returned future
发生在 future 的析构函数中。但是当我们使用std::pakaged_task
,其未来不会表现出相同的行为。
要完成打包任务,您必须显式调用get()
on future
对象来自packaged_task
.
现在我的问题是:
- 未来的内部实现可能是什么(思考
std::async
vs std::packaged_task
)?
- 为什么同样的行为没有应用于
future
从返回std::packaged_task
?或者,换句话说,相同的行为如何停止std::packaged_task
future
?
要查看上下文,请参阅下面的代码:
它不会等待完成countdown
任务。但是,如果我取消评论// int value = ret.get();
,它将完成countdown
这是显而易见的,因为我们实际上是在阻止返回的未来。
// packaged_task example
#include <iostream> // std::cout
#include <future> // std::packaged_task, std::future
#include <chrono> // std::chrono::seconds
#include <thread> // std::thread, std::this_thread::sleep_for
// count down taking a second for each value:
int countdown (int from, int to) {
for (int i=from; i!=to; --i) {
std::cout << i << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(1));
}
std::cout << "Lift off!" <<std::endl;
return from-to;
}
int main ()
{
std::cout << "Start " << std::endl;
std::packaged_task<int(int,int)> tsk (countdown); // set up packaged_task
std::future<int> ret = tsk.get_future(); // get future
std::thread th (std::move(tsk),10,0); // spawn thread to count down from 10 to 0
// int value = ret.get(); // wait for the task to finish and get result
std::cout << "The countdown lasted for " << std::endl;//<< value << " seconds.\n";
th.detach();
return 0;
}
如果我使用std::async
执行任务countdown
在另一个线程上,无论我是否使用get()
返回时future
对象或not,它总会完成任务。
// packaged_task example
#include <iostream> // std::cout
#include <future> // std::packaged_task, std::future
#include <chrono> // std::chrono::seconds
#include <thread> // std::thread, std::this_thread::sleep_for
// count down taking a second for each value:
int countdown (int from, int to) {
for (int i=from; i!=to; --i) {
std::cout << i << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(1));
}
std::cout << "Lift off!" <<std::endl;
return from-to;
}
int main ()
{
std::cout << "Start " << std::endl;
std::packaged_task<int(int,int)> tsk (countdown); // set up packaged_task
std::future<int> ret = tsk.get_future(); // get future
auto fut = std::async(std::move(tsk), 10, 0);
// int value = fut.get(); // wait for the task to finish and get result
std::cout << "The countdown lasted for " << std::endl;//<< value << " seconds.\n";
return 0;
}