我正在爲我的操作系統類寫一個包含線程的程序。它必須在一個線程中計算斐波那契數列的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);
}
好吧,我無法相信我錯過了。現在運行良好。謝謝。 – MathGuy