オペレーティングシステムクラスのスレッドを使用してプログラムを作成しています。それは1つのスレッドでフィボナッチシリーズの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