简体   繁体   English

从线程输出简单的向量

[英]Outputting Simple Vectors from Threads

I am currently attempting to understand multi-threading in C++ and want to return separate vectors from multiple threads so that a number of for loops can be ran simultaneously, I currently have the following code, and am struggling with the documentation, 我目前正在尝试了解C ++中的多线程,并希望从多个线程返回单独的向量,以便可以同时运行多个for循环,我目前有以下代码,并且在文档中苦苦挣扎,

#include <thread>
#include <iostream>
#include <vector>
#include <future>

using namespace std;


vector<int> task1(vector<int> v) { 
    for(int i = 0; i<10; i++)
    {
        v[i] = i;
    }
}

vector<int> task2(vector<int> v) { 
    for(int i = 10; i<20; i++)
    {
        v[i] = i;
    }

}

int main () 
{
    packaged_task<vector<int>()> taskA{task1}; 
    packaged_task<vector<int>()> taskB{task2};

    future<vector<int>()> future = taskA.get_future();
    future<vector<int>()> future2 = taskB.get_future();

    thread t1{move(taskA)};
    thread t2{move(taskB)};

    t1.join();
    t2.join();

return 0;
}

The aim of this code is to just get two vectors - one with 0-9 and the other 10-19. 此代码的目的是仅获得两个向量-一个向量为0-9,另一个向量为10-19。 If anyone has any pointers or simpler ways to perform this, they would be much appreciated. 如果任何人有任何指针或更简单的方法来执行此操作,将不胜感激。

Thanks for your time. 谢谢你的时间。

Async is probably the simplst. 异步可能是最简单的。 Your function needs to return a vector, not take one as an argument. 您的函数需要返回一个向量,而不是将其作为参数。 I coded it as a lambda, but a regular function is just as good. 我将其编码为lambda,但是常规函数也一样。 Ask if you have questions. 询问您是否有疑问。

#include <thread>
#include <future>
#include <vector>
int main() {
    using namespace std;
    using intvec = vector<int>;
    auto f= [](int start) {
        intvec s;
        for (int i = 0; i < 10; ++i)
            s.push_back(start + i);
        return s;
    };

    auto f1 = async(f, 0);
    auto f2 = async(f, 10);

    intvec s1 = f1.get();
    intvec s2 = f2.get();
}

... or if you prefer... ...或者如果您愿意...

#include <thread>
#include <future>
#include <vector>
using namespace std;

vector<int> task1() { 
    vector<int> v;
    for(int i = 0; i<10; i++)
        { v.push_back(i);}
    return v;
}

vector<int> task2() { 
    vector<int> v;
    for(int i = 10; i<20; i++)
        { v.push_back(i);}
    return v;
}
int main() {

    auto f1 = async(task1);
    auto f2 = async(task2);

    vector<int> s1 = f1.get();
    vector<int> s2 = f2.get();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM