std :: thread segmentation fault

时间:2017-03-27 18:39:03

标签: c++ multithreading c++11

我正在尝试使用线程来增加我的工作吞吐量,但是,我想出了一些我不知道原因的奇怪错误。以下不是我的代码,而是重现错误的最小代码:

的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--;
    }
}

当我尝试检索answers std::vector中的数据时,会发生细分错误。我在 CentOS Linux 7 上,并使用此命令进行编译:

g++ -std=c++11 main.cpp -o T.exe -lpthread

究竟发生了什么?我盯着它看了一会儿,看了一下 StackOverflow 上的一些页面,但我似乎无法理解发生了什么?

1 个答案:

答案 0 :(得分:0)

问题出在你的函数中打印矢量。您需要返回流以使其可流化。

template<typename T>
ostream& operator<<(ostream& os, const vector<T>& input)
{
    for (int i = 0; i < input.size(); i++)
    {
        os << input[i] << '\t';
    }
    return os;
}