在 c++ 中出现分段错误使用 pthreads
我正在为我的操作系统类编写一个带有线程的程序。它必须在一个线程中计算斐波那契数列的 n 个值,并在主线程中输出结果。当 n > 时,我不断收到分段错误。 10. 通过测试,我发现compute_fibonacci函数执行正确,但由于某种原因它永远不会进入main中的for循环。这是带有 cout 语句的代码,其中存在问题。我很感谢对此的任何帮助。
#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);
}
I'm writing a program with threads for my Operating Systems class. It must compute n values of the Fibonacci series in one thread and output the results in the main thread. I keep getting a segmentation fault when n > 10. From my testing, I discovered that the compute_fibonacci function is executed correctly, but for some reason it never gets to the for loop in main. Here's the code with cout statements where the problem is. I appreciate any help on this.
#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);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是声明一个用
argv[1]
中的整数值初始化的int
。看起来你想声明一个数组:This is declaring a single
int
initialized with the integral value fromargv[1]
. Looks like you want to declare an array instead:将第一行更改为:
Change the first line to: