C++ 11 Promise对象无效,但其未来对象既不返回值,也不会抛出异常
我有这个测试代码可以查看,如果一个承诺对象不在生命周期之外,那么它的未来对象会发生什么:
#include <chrono>
#include <future>
#include <iostream>
#include <thread>
using namespace std;
void getValue(future<int>& future) {
cout << "sub process 1 \n";
try {
cout << "sub process 2 \n";
int value = future.get();
cout << "sub process 3\n";
cout << value << endl;
} catch (future_error &e) {
cerr << e.code() << '\n' << e.what() << endl;
} catch (exception e) {
cerr << e.what() << endl;
}
cout << "sub process 4\n";
}
int main() {
thread t;
{
promise<int> plocal;
future<int> flocal = plocal.get_future();
t = thread(getValue, ref(flocal));
}
t.join();
return 0;
}
我希望在getValue
函数中,它会打印Future ::获取结果,或者抛出运行时异常并打印异常信息,因为Plocal
已在“ Main”中破坏了。
从行为上讲,该程序打印:
sub process 1
sub process 2
结束。
I've got this test code to see, if a promise object is out of lifecycle, what happen to its future object:
#include <chrono>
#include <future>
#include <iostream>
#include <thread>
using namespace std;
void getValue(future<int>& future) {
cout << "sub process 1 \n";
try {
cout << "sub process 2 \n";
int value = future.get();
cout << "sub process 3\n";
cout << value << endl;
} catch (future_error &e) {
cerr << e.code() << '\n' << e.what() << endl;
} catch (exception e) {
cerr << e.what() << endl;
}
cout << "sub process 4\n";
}
int main() {
thread t;
{
promise<int> plocal;
future<int> flocal = plocal.get_future();
t = thread(getValue, ref(flocal));
}
t.join();
return 0;
}
I expect that in getValue
function, it either prints future::get result, or throws out runtime exception and prints exception info, because plocal
has been destructed in "main".
Acturally, this program prints:
sub process 1
sub process 2
and ends.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的问题与
std :: Promise
或std :: Future
行为无关。您只需通过将
flocal
对象征用到线程,在线程中访问该flocal
对象来引起数据竞赛(并因此是未定义的行为),并且在主线程中也无需任何同步即可将其销毁。无论哪种类型或类型的对象
tlocal
是,这都不起作用。通过
std :: Future
通过std :: move
:随着此更改,
std :: Promise
将存储a <代码> std :: future_error 共享状态中的异常,get
在线程中的未来将接收并投掷。如果您用
std :: Ref
将某些内容传递给线程,则您始终必须确保引用的对象要列出线程,否则您需要确保有一些同步确定主线程何时可能破坏对象的机制。Your problem is not about
std::promise
orstd::future
behavior.You simply cause a data race (and consequently undefined behavior) by passing the
flocal
object by-reference to the thread, accessing it in the thread, but also destroying it in the main thread without any synchronization.This doesn't work no matter what type or kind of object
flocal
is.Pass the
std::future
by-value viastd::move
:With this change the destructor of
std::promise
will store astd::future_error
exception in the shared state andget
on the future in the thread will receive and throw it.If you pass something with
std::ref
to a thread you always have to make sure that the referenced object outlives the thread or you need to make sure that there is some synchronization mechanism to determine when the main thread may destroy the object.