小编Tim*_*Tim的帖子

如何在容器 C++ 中使用线程

如果我想编辑向量的每个元素,我可以使用for_each()循环遍历元素。现在的问题是,如何将这个任务分成两个线程?

我已经尝试了下面的方法,用 声明了一个线程for_each(),但是我遇到了错误。

例如,我想为向量的每个元素加 1。通过使用线程,似乎我错过了编译器不喜欢的东西。

#include <iostream>
#include <algorithm>
#include <vector>
#include <thread>

using namespace std;

int main()
{
    std::vector<int> nums;   //declare a vector
    nums.push_back(1);
    nums.push_back(2);
    nums.push_back(3);
    nums.push_back(4);     //push each element to the vector
    size_t i = (nums.size()/2);   //I want to separate the task into two thread 
    std::thread t1(std::for_each(nums.begin(),nums.begin()+i,[](int& num){
        num++;
    }));
    std::thread t2(std::for_each(nums.begin()+i,nums.end(),[](int& num){
        num++;
    }));
    
    t1.join();
    t2.join();

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我收到这两个错误:

未能专门化函数模板 'unknown-type std::invoke(_Callable &&) noexcept(<expr>)'

invoke': 找不到匹配的重载函数

如果我不能以这种方式做线程,那么正确的方法是什么?

c++ algorithm multithreading stl stdvector

3
推荐指数
1
解决办法
81
查看次数

标签 统计

algorithm ×1

c++ ×1

multithreading ×1

stdvector ×1

stl ×1