问题
I want to use C++11 std::thread
. I am writing a code to parse JSON files and the parsing is not dependent on each other. I have 900 files and to increase the speed of execution I want to create as many threads and make the execution parallel.
My problem is at the moment the function I want to pass to the std::thread
is a function of a class and it returns the parsed object as a JSON object from which I create a std::vector
.
I googled 'returning values from threads' and I am getting the tutorials of using async
, is there no other way other than async? I went through the async tutorials I am not able to understand how it's launching new threads.
Following is my code:
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);
}
I want to pass the function parse(jsonFile)
to my threads numbering the count of total JSON files, and return the json object, which I will use to create a std::vector
of jsonObjects.
How can I do this?
回答1:
Using std::async
seems like a good approach, since it return a std::future
from which you can get the returned value.
Here is a short example that you could use as an idea to get going.
#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 also has member functions like valid, wait, wait_for and wait_until if you want more flexibility in how you retrieve the value.
来源:https://stackoverflow.com/questions/65828746/how-do-i-return-a-class-object-from-a-thread-and-create-a-vector-of-returned-obj