/** description: ex2.c* copyright: (C) by ocean* Function: 利用管道实现f(x,y) = f(x) + f(y) 其中: f(x) = f(x-1) * x (x >1) f(x)=1 (x=1) f(y) = f(y-1) + f(y-2) (y> 2) f(y)=1 (y=1,2)*/ #include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <pthread.h> void task1(int *); //线程1执行函数原型 void task2(int *); //线程2执行函数原型 void task3(int *);//线程3执行函数原型
int fx(int x){ if(x==1) return 1; else return x*fx(x-1); } int fy(int y){ if(y==1||y==2) return 1; else return fy(y-1)+fy(y-2); }
int pipe1[2],pipe2[2],pipe3[2],pipe4[2];//存放两个无名管道标号 pthread_t thrd1,thrd2,thrd3;//存放两个线程标识 int main(int argc,char *arg[]) { int ret; int num1,num2,num3; //使用pipe()系统调用建立3个无名管道。建立不成功程序退出,执行终止 if(pipe(pipe1) < 0){ perror("pipe not create"); exit(EXIT_FAILURE); } if(pipe(pipe2) < 0){ perror("pipe not create"); exit(EXIT_FAILURE); } if(pipe(pipe3) < 0){ perror("pipe not create"); exit(EXIT_FAILURE); } if(pipe(pipe4) < 0){ perror("pipe not create"); exit(EXIT_FAILURE); } //使用pthread_create系统调用建立3个线程。建立不成功程序退出,执行终止 num1 = 1 ; ret = pthread_create(&thrd1,NULL,(void *) task1,(void *) &num1); if(ret){ perror("pthread_create: task1"); exit(EXIT_FAILURE); } num2 = 2 ; ret = pthread_create(&thrd2,NULL,(void *) task2,(void *) &num2); if(ret){ perror("pthread_create: task2"); exit(EXIT_FAILURE); } num3 = 3 ; ret = pthread_create(&thrd3,NULL,(void *) task3,(void *) &num3); if(ret){ perror("pthread_create: task3"); exit(EXIT_FAILURE); } //挂起当前线程切换到thrd3线程 pthread_join(thrd3,NULL); //挂起当前线程切换到thrd1线程 pthread_join(thrd1,NULL); //挂起当前线程切换到thrd2线程 pthread_join(thrd2,NULL); exit(EXIT_SUCCESS); } //线程1执行函数,它首先向管道写,然后从管道读 void task1(int *num) { int a,x=1; int n=1; do{ int xx = fx(x); write(pipe1[1],&xx,sizeof(int)); printf("thread f(x) equals : %d x=%d/n",xx,x); read(pipe3[0],&a,sizeof(int)); x++; n++; }while(n<=9); //读写完成后,关闭管道 close(pipe1[1]); close(pipe3[0]); }
void task2(int * num) { int b,y=1; int n=1; do{ int yy = fy(y); write(pipe2[1],&yy,sizeof(int)); printf("thread f(y) equals : %d y=%d/n",yy,y); read(pipe4[0],&b,sizeof(int)); y++; n++; }while( n<=9 ); //读写完成后,关闭管道 close(pipe4[0]); close(pipe2[1]); } void task3(int *num){ int xx,yy; int n=1; int a =0,b=0; do{ read(pipe1[0],&xx,sizeof(int)); read(pipe2[0],&yy,sizeof(int));
int xy = xx+yy; printf("thread f(x,y) equals: %d/n",xy); write(pipe3[1],&a,sizeof(int)); write(pipe4[1],&b,sizeof(int)); n++; }while(n<=9); //读写完成后,关闭管道 close(pipe1[1]); close(pipe2[0]); close(pipe3[1]); close(pipe4[1]); }