2009-11-24 57 views
2

我收到錯誤「未定義的引用到'pthread_attr_init'」,即使它應該在pthread.h中。這是在應該爲Pthreads設置的UNIX環境中。此外,是一個void *指向當前矩陣的好方法嗎?這是我的代碼,有什麼想法?Pthreads C++編譯錯誤

#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 */ 

} 
+0

你使用了哪些編譯器標誌? – Suppressingfire 2009-11-24 05:03:25

回答

5

這將取決於你的平臺上,但我會嘗試添加-lpthread你的鏈接命令,那就是在Linux和其他一些必需的。您的程序在此編譯爲g++ foo.cc -lpthread

+2

對於pthreads(特別是),不是編譯器開關-pthread,還是最近發生了變化? – Suppressingfire 2009-11-24 05:29:35

+0

這可以在一些編譯器/平臺上工作......例如,Sun的cc用於像這樣工作。我認爲gcc支持它也與其他人兼容。 – asveikau 2009-11-24 05:45:21