I'm learning to use thread in c++
I created a very long vector with integers and set another integer x. And I want to calculate the difference between that integer and the integers in the vector.
However, in my implementation, the function using two threads is slower than a single thread function. I wonder why is the reason, and how can I implement threading correctly so it does run faster.
Here's the code:
#include <iostream>
#include <vector>
#include <thread>
#include <future>
#include <math.h>
using namespace std;
vector<int> vector_generator(int size) {
vector<int> temp;
for (int i = 0; i < size; i++) {
temp.push_back(i);
}
return temp;
}
vector<int> dist_calculation(int center, vector<int> &input, int start, int end) {
vector<int> temp;
for (int i = start; i < end; i++) {
temp.push_back(abs(center - input[i]));
}
return temp;
}
void multi_dist_calculation(int center, vector<int> &input) {
int mid = input.size() / 2;
vector<int> temp1(input.begin(), input.begin() + mid);
vector<int> temp2(input.begin()+mid, input.end());
auto future1 = async(dist_calculation, center, temp1, 0, mid);
auto future2 = async(dist_calculation, center, temp2, 0, mid);
vector<int> result1 = future1.get();
vector<int> result2 = future2.get();
return;
}
int main() {
vector<int> v1 = vector_generator(1000000000);
vector<int> result;
multi_dist_calculation(0, v1);
//dist_calculation(50, v1, 0, v1.size());
return 0;
}
Update #1
Added suggestions of std::launch::async & reserve(), and it does make the code faster. But the 2-threaded function is still slower than single threaded one. Can I say in this kind of calculation, single-threaded is faster?
#include <iostream>
#include <vector>
#include <thread>
#include <future>
#include <math.h>
using namespace std;
vector<int> vector_generator(int size) {
vector<int> temp;
temp.reserve(size);
for (int i = 0; i < size; i++) {
temp.push_back(i);
}
return temp;
}
vector<int> dist_calculation(int center, vector<int> &input, int start, int end) {
vector<int> temp;
temp.reserve(end - start);
for (int i = start; i < end; i++) {
temp.push_back(abs(center - input[i]));
}
return temp;
}
void multi_dist_calculation(int center, vector<int> &input) {
int mid = input.size() / 2;
auto future1 = async(std::launch::async, dist_calculation, center, input, 0, mid);
auto future2 = async(std::launch::async, dist_calculation, center, input, mid, input.size());
vector<int> result1 = future1.get();
vector<int> result2 = future2.get();
return;
}
int main() {
vector<int> v1 = vector_generator(1000000000);
vector<int> result;
int center = 0;
multi_dist_calculation(center, v1);
//dist_calculation(center, v1, 0, v1.size());
return 0;
}
asynccalls. Isn't that UB? Try usingasync(std::launch::async, dist_calculation, center, temp1, 0, mid);.