If I want to edit each element of a vector, I can use for_each() to loop through the elements. The problem now is, how can I separate this task into two threads?
I've tried the way below, declaring a thread with for_each(), but I'm getting errors for that.
For example, I'd like to add 1 to each element of the vector. By using the threads, it seems like I'm missing something that the compiler does not like.
#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;
}
I'm getting these two errors:
Failed to specialize function template 'unknown-type std::invoke(_Callable &&) noexcept(<expr>)'
and
invoke': no matching overloaded function found
If I cannot do the threads in this way, what's the right way?