-3

我正在尝试学习 C 编程和多线程。我开始编写一些基本的东西 [如下所示],但我陷入了困境。有人可以帮帮我吗?

程序.c

#include <string.h>
#include <stdio.h>
#include <pthread.h>
#define NUM_THREADS 4

void *main_thread(void *threadID) {
    long tid;
    tid = (long)threadID;
    printf("main thread #%ld!\n", tid);
    pthread_exit(NULL);

}

void *first_thread(void *threadID) {
    long tid;
    tid = (long)threadID;
    printf("first thread #%ld!\n", tid);
    pthread_exit(NULL);

}

void *second_thread(void *threadID) {
    long tid;
    tid = (long)threadID;
    printf("second thread #%ld!\n", tid);
    pthread_exit(NULL);

}

void *last_thread(void *threadID) {
    long tid;
    tid = (long)threadID;
    printf("last thread #%ld!\n", tid);
    pthread_exit(NULL);

}



int main () {
    pthread_t threads[NUM_THREADS];
    int rc;
    long t;

    for (t=0; t < NUM_THREADS; t++) {
        printf("In main Function creating thread %ld\n", t);
        rc = pthread_create(&threads[t], NULL, first_thread, (void *)t);
        if (rc) {
            printf("ERROR; Return code from pthread_create is %d\n", rc);
            exit(-1);
        }

    }


    pthread_exit(NULL);
    return 0;
}

当我发现新事物时,我将不断更新上面的代码*嘿伙计们。我没有正确编译它,但现在我想通了。gcc -pthread -o main main.c

4

1 回答 1

1

此代码将通过计算其系列项来计算 e^x 的值,在每个项中,我们需要计算一个数字的幂(在此程序中为 x)和每个对应幂的阶乘。

因为这两个计算是独立的,所以我们为这两个函数创建了两个线程,它们将并行运行。

在计算这两个函数的值(这两个线程的结尾)之后,我们需要合并结果(我的意思是幂/阶乘),然后我们将所有这些结果添加到另一个并行线程中,该线程将在这两个线程之后运行。

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

long double x,fact[150],pwr[150],s[1];
int i,term;

void *Power(void *temp)
{   
    int k;

    for(k=0;k<150;k++)
    {
        pwr[k] = pow(x,k);
    //printf("%.2Lf\n",pwr[k]);
    } 

    return pwr;
}

void *Fact(void *temp)
{
    long double f;
    int j;

    fact[0] = 1.0;

    for(term=1;term<150;term++)
    {
        f = 1.0;

        for(j=term;j>0;j--)
        f = f * j;

        fact[term] = f;
        //printf("%.2Lf\n",fact[term]);
    }

   return fact;
}

void *Exp(void *temp)
{
    int t;
    s[0] = 0;   

    for(t=0;t<150;t++)
    s[0] = s[0] +  (pwr[t] / fact[t]);

    return s;
}

int main(void)
{
    pthread_t thread1,thread2,thread3;  

    printf("Enter the value of x (between 0 to 100) (for calculating exp(x)) : ");
    scanf("%Lf",&x);

    printf("\nThreads creating.....\n");
    pthread_create(&thread1,NULL,Power,NULL); //calling power function
    pthread_create(&thread2,NULL,Fact,NULL);  //calling factorial function
    printf("Threads created\n");

    pthread_join(thread1,NULL);
    pthread_join(thread2,NULL);
    printf("Master thread and terminated threads are joining\n");
    printf("Result collected in Master thread\n");

    pthread_create(&thread3,NULL,Exp,NULL);
    pthread_join(thread3,NULL);

    printf("\nValue of exp(%.2Lf) is : %Lf\n\n",x,s[0]);

    exit(1);
}
于 2013-10-15T07:20:46.013 回答