如何从线程返回类对象并创建返回对象的向量?

编程入门 行业动态 更新时间:2024-10-11 03:22:25
本文介绍了如何从线程返回类对象并创建返回对象的向量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想使用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.

更多推荐

如何从线程返回类对象并创建返回对象的向量?

本文发布于:2023-08-04 21:44:15,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1299874.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:对象   向量   线程

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!