C ++使用promise从线程返回多个值,将来吗?

Q12*_*123 2 c++ multithreading future promise c++11

我想做的是从每个线程返回一个值。但是,它具有此异常消息。

libc++abi.dylib: terminating with uncaught exception of type std::__1::future_error: Operation not permitted on an object without an associated state.
Run Code Online (Sandbox Code Playgroud)

代码看起来像这样。

vector<thread> t;
promise<class_name> promises;
vector<future<class_name>> futures;

for(int i = 0; i < NumberOfThreads; i++)
{
    futures.push_back(promises.get_future());
    t.push_back(thread(MyFunction ,i , pointList, std::move(promises)));
}
Run Code Online (Sandbox Code Playgroud)

MyFunction看起来像这样。

void MyFunction(int index, const vector<Point>& pointList, promise<class_name>&& p)
{
....
p.set_value(classObj);
}
Run Code Online (Sandbox Code Playgroud)

如果使用线程,则可以正常工作而不会出现异常消息。

有解决这个问题的主意吗?

Bey*_*ios 5

将承诺移至其线程后,请勿重用。将promise移动到循环体内,您的代码应运行良好:

vector<thread> t;
vector<future<class_name>> futures;

for(int i = 0; i < NumberOfThreads; i++)
{
    promise<class_name> p;
    futures.push_back(p.get_future());
    t.push_back(thread(MyFunction ,i , pointList, std::move(p)));
}
Run Code Online (Sandbox Code Playgroud)