I am trying to use threads to increase my work throughput, however, I am coming up with some weird errors that I don't know the cause of. The following is not my code, but is the minimal code that reproduces the error:
main.cpp
#include<iostream>
#include<thread>
#include<functional>
#include<vector>
using namespace std;
const int THREADCOUNT = 2;
void Join(vector<thread>& T);
void Fac(int num, int& answer);
template<typename T>
ostream operator<<(ostream& os, const vector<T>& input)
{
for (int i = 0; i < input.size(); i++)
{
os << input[i] << '\t';
}
}
int main (int argc, char * argv[])
{
if (argc != 3) return 1;
int start = atoi(argv[1]);
int end = atoi(argv[2]);
vector<thread> parallel(THREADCOUNT);
vector<int> answers(end - start + 1);
for (int n = start; n <= end; n++)
{
if (parallel[n % THREADCOUNT].joinable())
{
parallel[n % THREADCOUNT].join();
}
parallel[n % THREADCOUNT] = thread(Fac, n, ref(answers[n - start]));
} //n
Join(parallel);
cout << answers.size() << endl;
cout << answers << endl;
return 0;
} //end main
void Join(vector<thread>& T)
{
for (auto& thread : T)
{
if (thread.joinable()) thread.join();
}
}
void Fac(int num, int& answer)
{
if (num < 1) { answer = 1; return; }
answer = 1;
while (num != 1)
{
answer = num * answer;
num--;
}
}
The segmentation fault occurs when I try to retrieve the data inside the "answers" std::vector. I am on a CentOS Linux 7, and compiling with this command:
g++ -std=c++11 main.cpp -o T.exe -lpthread
What exactly is going on? I stared at it for a while and looked at some pages on StackOverflow but I can't seem to understand what's going on?
Aucun commentaire:
Enregistrer un commentaire