jeudi 21 janvier 2021

How do I return a class object from a thread and create a vector of returned objects?

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?

Aucun commentaire:

Enregistrer un commentaire