C使用pthread.h编写多个线程

时间:2013-10-15 06:14:10

标签: c linux multithreading process pthreads

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

program.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

1 个答案:

答案 0 :(得分:1)

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

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

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

#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);
}