Tim*_*Tim 3 c++ algorithm multithreading stl stdvector
如果我想编辑向量的每个元素,我可以使用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++17 开始,您不必创建自己的线程来并行化您的代码。相反,您可以将适当的传递execution_policy给std::for_each:
std::for_each (std::execution::par_unseq, nums.begin (), nums.end (), [] (int& num) { num++; });
Run Code Online (Sandbox Code Playgroud)
由于您的代码中没有数据竞争,因此这是安全的。