我想使用C ++ 11 std::thread
。我正在编写代码以解析JSON文件,并且解析不相互依赖。我有900个文件,并且为了提高执行速度,我想创建尽可能多的线程并使执行并行。
我的问题是,目前要传递给的std::thread
函数是类的函数,它将返回的已解析对象作为JSON对象返回,从中创建std::vector
。
我用谷歌搜索“从线程中返回值”,并且正在使用的教程,async
除了异步,别无其他方法吗?我看了异步教程,我不明白它是如何启动新线程的。
以下是我的代码:
for (auto it = jsonFilesList.begin(); it != jsonFilesList.end(); it++) {
std::ifstream jsonFile;
jsonFile.open(*it);
jf = json::parse(jsonFile);
jsonFile.close();
jsonObjects.push_back(jf);
}
我想将函数传递parse(jsonFile)
给我的线程,以对JSON文件总数进行编号,然后返回json对象,我将使用它创建std::vector
jsonObjects。
我怎样才能做到这一点?
使用std::async
似乎是一种好方法,因为它返回一个std::future
,您可以从中获取返回的值。
这是一个简短的示例,您可以以此为出发点。
#include <iostream>
#include <future>
#include <vector>
int doWork(int i) {
return i*2;
}
int main()
{
std::vector<int> results;
std::vector<std::future<int>> work;
for (int i = 0; i < 10; ++i) {
work.emplace_back(std::async(std::launch::async, &doWork, i));
}
// do some other stuff, or nothing
// before getting the results from all the futures
for (auto& future : work) {
results.emplace_back(future.get());
}
for(auto i : results) {
std::cout << i << '\n';
}
return 0;
}
如果希望在获取值的方式上具有更大的灵活性,std :: future还具有有效,等待,wait_for和wait_until等成员函数。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句