【发布时间】:2011-10-03 07:14:48
【问题描述】:
鉴于下面的代码,如果我使用 n>16 运行它,我会遇到分段错误。
我认为它与堆栈有关,但我无法弄清楚。谁能帮我一把?代码不是我的,而且真的不重要。我只想有人帮我处理正在发生的事情。 This SO question 非常相似,但没有足够的信息(发布答案的人简短地谈到了问题,然后继续谈论不同的语言)。此外,请注意,使用两个 gig 并且没有递归,我可以(如果我做得对的话)成功地创建了 16000 多个线程(尽管操作系统只创建了大约 500 个并运行了大约 300 个)。无论如何,我在哪里得到段错误,为什么?谢谢。
#include <pthread.h>
#include <stdio.h>
static void* fibonacci_thread( void* arg ) {
int n = (int)arg, fib;
pthread_t th1, th2;
void* pvalue; /*Holds the value*/
switch (n) {
case 0: return (void*)0;
case 1: /* Fallthru, Fib(1)=Fib(2)=1 */
case 2: return (void*)1;
default: break;
}
pthread_create(&th1, NULL, fibonacci_thread, (void*)(n-1));
pthread_create( &th2, NULL, fibonacci_thread, (void*)(n-2));
pthread_join(th1, &pvalue);
fib = (int)pvalue;
pthread_join(th2, &pvalue);
fib += (int)pvalue;
return (void*)fib;
}
int main(int argc, char *argv[])
{
int n=15;
printf ("%d\n",(int)fibonacci_thread((void*)n));
return 0;
}
【问题讨论】:
-
首先检查
pthread_create和pthread_join的返回值。 (只要assert,如果你愿意,他们会返回零。) -
另外,这是在 32 位 Linux 系统上吗?我认为 pthreads 为每个线程分配了大约 2 兆的堆栈。这只是虚拟内存,不是物理内存,但它仍然会将您限制在大约 2000 个线程左右,然后才会出现问题。
标签: c stack pthreads segmentation-fault