如何从线程返回类对象并创建返回对象的向量? [英] How do I return a class object from a thread and create a vector of returned objects?

查看:51
本文介绍了如何从线程返回类对象并创建返回对象的向量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用C ++ 11 std :: thread .我正在编写代码以解析JSON文件,并且解析不相互依赖.我有900个文件,为了提高执行速度,我想创建尽可能多的线程并使执行并行.

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.

我的问题是此刻我要传递给 std :: thread 的函数是一个类的函数,它将解析后的对象作为JSON对象返回,从中创建 std :: vector .

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.

我用Google搜索从线程中返回值",并且得到了使用 async 的教程,除了异步,别无其他方法吗?我经历了异步教程,我无法理解它是如何启动新线程的.

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.

以下是我的代码:

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 :::.

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.

我该怎么做?

推荐答案

使用 std :: async 似乎是一种好方法,因为它返回了 std :: future 从中可以获得返回值.

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 还具有有效,等待,如果希望在获取值的方式上具有更大的灵活性,请使用wait_for和wait_until.

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.

这篇关于如何从线程返回类对象并创建返回对象的向量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆