【发布时间】:2015-10-23 01:17:57
【问题描述】:
这段代码用于使用多线程的斐波那契数列,但它显示了错误。你能检查一下并告诉我我必须做些什么来解决这个问题
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
int arr[100];/* array*/
typedef struct {
int input;
int output[100];
} thread_args;
void *thread_func ( void *ptr )/*child thread */
{
int i = ((thread_args *) ptr)->input;
int x;
((thread_args *) ptr)->output[0]=0;
((thread_args *) ptr)->output[1]=1;
for(x=2;x<i;x++)
{
/* ((thread_args *) ptr)->output[x]=
((thread_args *) ptr)->output[x-1]
+((thread_args *) ptr)->output[x-2]; */
}
return NULL;
}
int main(int argc, char *argv[])
{
pthread_t thread;
thread_args args;
int status;
int x;
int result;
int thread_result;
if (argc < 2) return 1;
int n = atoi(argv[1]);
args.input = n;
status = pthread_create(&thread,NULL,thread_func,(void*) &args );
// main can continue executing
// Wait for the thread to terminate.
pthread_join(thread, NULL);
for(x=0;x<n;x++)
{
arr[x]=args.output[x];/* get the result*/
printf("Fibonacci is %d.\n", arr[x]);/*print all numbers*/
}
}
return 0;
}
【问题讨论】:
-
欢迎来到 SO。请更详细地描述您遇到的错误和位置。您也可以使用编辑按钮来删除一式三份的措辞并缩进您的代码,使其变得可读。谢谢。
-
开始,在编译时,始终启用所有警告,然后修复这些警告。 (对于 gcc,至少使用:
-Wall -Wextra -pedantic -std-c99) -
发布的代码甚至还没有开始编译。第一个问题是 main() 中的 'for()' 循环之后的额外右大括号 '}'
-
为了可读性,请一致地缩进代码。建议在每个缩进级别使用 4 个空格。 4 个空格允许在不占用可用页面宽度的情况下进行多个级别的缩进,并且即使使用可变宽度字体也足够宽。建议在每个左大括号后缩进:'{' 并且在每个右大括号之前不缩进:'}' 建议在代码块周围留一个空行(for、while、do...while、if、else 等)
-
你没有提到你得到了什么错误。请按照@JensGustedt 的建议添加错误的详细信息。如果您的错误是计算出的斐波那契数列值的错误值,请注意用于“输出”和“arr”的数据类型为“int”,它将正常工作到斐波那契数列中的第 46 个元素。对于更高的元素,您需要使用 64 位数据类型(unsigned long long int 或 uint64_t),然后在打印值时调用 printf() 中的 '%llu' 说明符。
标签: c arrays multithreading pthreads posix