试图用线程计算斐波纳契数.它总是返回1.有什么建议吗?
我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
/* compile with -lpthread */
void* fibo (void* param) {
int a,b,n;
pthread_t thread_a, thread_b;
int ret;
n = (int) param;
if (n>1)
{ pthread_create(&thread_a,NULL,fibo,(void*)(n-1));
pthread_create(&thread_b,NULL,fibo,(void*)(n-2));
pthread_join(thread_a,(void**)&a);
pthread_join(thread_b,(void**)&b);
ret=a+b;
}
else ret=1;
return (ret);
/*pthread_exit((void**)ret);*/
}
int main(int argc,char* argv[]) {
pthread_t thread_id;
int n,ret;
n=atoi(argv[1]);
pthread_create(&thread_id,NULL,fibo,(void*)n);
pthread_join(thread_id,(void**)&ret);
printf("s(%d)=%d\n",n,ret);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我猜你可能在64位系统上.
您的问题出在pthread_join中:
int n,ret;
pthread_join(thread_id,(void**)&ret);
Run Code Online (Sandbox Code Playgroud)
在64位系统上,ints是32位,但void*s是64位.所以你试图在一个32位宽的变量中存储64位.结果,你覆盖堆栈上的其他位置,通常只会造成大量的事情.确保将值检索为true,void *并且事情应该更好.更好的是,使用void*指针作为真正的指针; 例如,您可以将指针传递给int作为线程函数参数的指针,并将其用作参数,然后将结果写入同一位置.
顺便提一下,即使没有任何警告开关,GCC也会对此发出警告:
test.c:30: warning: cast to pointer from integer of different size
Run Code Online (Sandbox Code Playgroud)
请不要忽略这些警告.