2016-10-24 5 views
-3

C 프로그래밍 언어를 사용하여 새로 운영 체제를 연구하고 Linux 시스템에서 프로세스/스레드를 만들었지 만 (필자가 사용할 것으로 예상되는 것) 코드에 문제가 있습니다. 쓰기 위해 노력하고 :C, 피보나치 프로그램의 멀티 스레딩

여기 우분투 시스템에 기록 된 내 코드입니다 :

#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 시간 제로 무엇인지. 그리고 주요 질문은 어떻게 각각의 스레드가 사용자가 입력 한 용어의 수 (동시에 스레드의 수)에 따라 피보나치 시리즈의 "하나의 용어"만 쓰게 할 수 있습니까? 이런 종류의 프로그램을 구현하는 다른 더 논리적 인 방법이 있습니까?

+0

"threadCount times zeros"란 무엇을 의미합니까? –

+2

피보나치 시리즈에는 닫힌 폼 솔루션이 있으므로 루프가 훨씬 적고 스레드가 필요하지 않습니다. –

+0

threadCount가 3이면 예를 들어 세 번 0이 인쇄됩니다. – adropintheocean

답변

0

각 스레드의 work에 대한 인수로 lpParameter[i]을 사용하지만 fibonacci을 호출 할 때 해당 내용을 무시하십시오.