2011-10-25 45 views
0

我正在爲我的操作系統類寫一個包含線程的程序。它必須在一個線程中計算斐波那契數列的n個值,並在主線程中輸出結果。當n> 10時,我總是收到分段錯誤。從我的測試中,我發現compute_fibonacci函數是正確執行的,但由於某些原因,它永遠不會到達main中的for循環。這裏的問題是cout語句的代碼。我很感激這方面的幫助。使用pthreads在C++中獲取一個段錯誤

#include <iostream> 
#include <pthread.h> 
#include <stdlib.h> 
#include <stdio.h> 

void *compute_fibonacci(void *); 

int *num; 

using namespace std; 

int main(int argc, char *argv[]) 
{ 
    int i; 
    int limit; 
    pthread_t pthread; 
    pthread_attr_t attr; 

    pthread_attr_init(&attr); 
    pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM); 

    num = new int(atoi(argv[1])); 
    limit = atoi(argv[1]); 

    pthread_create(&pthread, NULL, compute_fibonacci, (void *) limit); 
    pthread_join(pthread, NULL); 

    cout << "This line is not executed" << endl; 

    for (i = 0; i < limit; i++) { 
     cout << num[i] << endl; 
    } 

    return 0; 
} 

void *compute_fibonacci(void * limit) 
{ 
    int i; 

    for (i = 0; i < (int)limit; i++) { 
     if (i == 0) { 
      num[0] = 0; 
     } 

     else if (i == 1) { 
      num[1] = 1; 
     } 

     else { 
      num[i] = num[i - 1] + num[i - 2]; 
     } 
    } 

    cout << "This line is executed" << endl; 

    pthread_exit(0); 
} 

回答

2
num = new int(atoi(argv[1])); 

這是聲明與來自argv[1]積分值初始化的單一int。貌似要聲明一個數組來代替:

num = new int[ atoi(argv[1]) ]; 
+0

好吧,我無法相信我錯過了。現在運行良好。謝謝。 – MathGuy

1
num = new int(atoi(argv[1])); 
limit = atoi(argv[1]); 

更改第一行:

num = new int[atoi(argv[1])];