Pthreads C++编译错误

3

我遇到了错误“undefined reference to `pthread_attr_init'”,尽管这个函数应该在pthread.h中。这是在一个应该设置为Pthreads的UNIX环境中发生的。另外,使用void*指向当前矩阵是一个好方法吗?以下是我的代码,请问有什么建议吗?

#include <cstdlib>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <time.h>
#include <limits.h>
#include <pthread.h>
#include <semaphore.h>

#define MAX_MATRIX_SIZE     256
#define MAX_THREADS         64

using namespace std;

void *StripProcessor(void *);
void Barrier();
void InitMatrix(int rows, int cols);

int main(int argc, char *argv[])
{
    /* Get command line params */
    if (argc != 3) {
        cout << "Error: need 2 command line params." << endl;
        getchar();
        return 1;
    }
    int numThreads = atoi(argv[1]);
    double epsilon = atof(argv[2]);


    /* Locals hang here */
    pthread_mutex_t barrier;
    pthread_cond_t leave;
    int numWaiting = 0;

    int rows;
    int cols;
    int stripSize;
    int lastStripSize;
    int iterations;

    double matrix1[MAX_MATRIX_SIZE][MAX_MATRIX_SIZE];
    double matrix2[MAX_MATRIX_SIZE][MAX_MATRIX_SIZE];
    void *currentMatrix = matrix1; //????????????????
    double stripMaxDiff[MAX_THREADS];

    clock_t start;
    clock_t finish;


    /* Get rows and cols from standard in */
    string buffer;
    getline(cin, buffer);
    istringstream myStream(buffer);
    myStream >> rows;
    myStream >> cols;
    cout << rows << " " << cols << endl;
    getchar();


    /* Set locals */
    if (rows % numThreads == 0) {
        stripSize = rows / numThreads;
        lastStripSize = 0;
    }
    else {
        stripSize = rows / numThreads + 1;
        if (rows % stripSize == 0) {
            numThreads = rows / stripSize;
            lastStripSize = 0;
        }
        else {
            numThreads = rows / stripSize + 1;
            lastStripSize = rows - (stripSize * (numThreads - 1));
        }
    }


    /* Set up threads */
    vector<pthread_t> threadID;
    pthread_attr_t attr;
    pthread_attr_init(&attr);
    pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM);


    /* Init mutex, CV, and matrix */
    pthread_mutex_init(&barrier, NULL);
    pthread_cond_init(&leave, NULL);
    //InitMatrix(rows, cols);


    /* Create threads and wait for completion */
    start = clock();

    /*for (unsigned int i = 0; i < threadID.size; i++)
        pthread_create(&threadID[i], &attr, StripProcessor, (void *) i);
    for (unsigned int i = 0; i < threadID.size; i++)
        pthread_join(threadID[i], NULL);*/

    finish = clock();


    /* Print results */

}

你使用了哪些编译器标志? - Suppressingfire
1个回答

6

这将取决于您的平台,但是我建议在链接命令中添加 -lpthread,因为在Linux和其他一些操作系统中需要它。您的程序应该像这样编译:g++ foo.cc -lpthread


2
对于pthread(具体而言),编译器开关不是-pthread吗?或者最近有改变吗? - Suppressingfire
这在一些编译器/平台上是可以工作的...例如Sun的cc曾经就是这样工作的。我认为gcc也支持它以便与其他编译器兼容。 - asveikau

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接