【问题标题】:Multithreading in C, Fibonacci ProgramC中的多线程,斐波那契程序
【发布时间】:2017-03-06 15:06:40
【问题描述】:

我刚刚开始学习操作系统并使用 C 编程语言在 Linux 系统上创建进程/线程(这是我们期望使用的),但是我一直在尝试编写的代码存在一些问题:

这是我在 Ubuntu 系统上编写的代码:

    #include <pthread.h>
    #include <stdlib.h>
    #include <stdio.h>

    int total = 0;

   typedef struct
   {
    int start;
    int end;
    int threadNo;
   }THREAD_PARAMETERS;

  void *work(void *parameters);
  int threadCount;

 int main(int argc, char* argv[])
 {

      printf("please give the number of terms you want to diplay..");
      scanf("%d", &threadCount);

     pthread_t tid[threadCount];
     pthread_attr_t attr[threadCount];

     THREAD_PARAMETERS* lpParameter;

      int n;

    lpParameter = malloc(sizeof(THREAD_PARAMETERS)* threadCount);

    int  i=0;

    for(i=0; i<threadCount; i++)
    {
     lpParameter[i].start = 0;
     lpParameter[i].end = 1;
     lpParameter[i].threadNo = i + 1;

     pthread_attr_init(&attr[i]);
     pthread_create(&tid[i],&attr[i],work,&lpParameter[i]); 
    }

    for(i=0; i<threadCount; i++)
    {
    pthread_join(tid[i],NULL);
    }
    return 1;
    }



    void fibonacci(int a)
    {
     int  prev_term = 0, current_term = 1, next_term = 0;

     if(a==0){
     printf("%d\n",prev_term);

     }
     else if(a==1){

     next_term=current_term+prev_term;
     printf("%d\n",current_term);
     prev_term=current_term;
     current_term=next_term;

    void *work(void * parameters)
    {
    THREAD_PARAMETERS* param = (THREAD_PARAMETERS*)parameters;
    fibonacci(threadCount);
    pthread_exit(0);
    }

问题是程序使用 threadCount 变量计数,但程序打印的只是 threadCount 乘以零。 主要问题是如何根据用户输入的术语数(同时是线程数)使每个线程写入斐波那契数列的“仅一个术语”?还有其他更合乎逻辑的方式来实现这种程序吗?

【问题讨论】:

  • “threadCount 乘以零”是什么意思?
  • 请注意,斐波那契数列有一个封闭形式的解决方案,因此不需要循环,更少的线程。
  • 但是,如果您确实以最简单的方式实现基于线程的斐波那契计算器,那么您从线程中获得的收益很少,如果有的话,因为您'将需要序列化线程的操作。
  • 在斐波那契计算中没有分而治之的优势。您可以做的最好的事情是启动一个线程来预先计算所有答案并将它们放在一个表中,而另一个线程实际处理查询并进行表查找或等待计算线程输入答案。
  • 提供的代码无效 -- 函数fibonacci() 似乎被截断了。

标签: c linux multithreading


【解决方案1】:

您使用lpParameter[i] 作为每个线程的work 的参数,但在调用fibonacci 时忽略其内容。

【讨论】:

    猜你喜欢
    • 2020-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-20
    相关资源
    最近更新 更多