代码:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <math.h>
int done=0;
double a,b,c,d;
double x1,x2;
pthread_mutex_t m=PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond=PTHREAD_COND_INITIALIZER;
void thr_exit(){
pthread_mutex_lock(&m);
done++;
if(done==2)
pthread_cond_signal(&cond);
pthread_mutex_unlock(&m);
}
void *child1_add(void *arg){
printf("child1\n");
if(d>=0)
x1=(-b+d)/ (2 * a);
thr_exit();
return NULL;
}
void *child2_sub(void *arg){
printf("child2\n");
if(d>=0)
x2=(-b-d)/ (2 * a);
thr_exit();
return NULL;
}
void thr_join(){
pthread_mutex_lock(&m);
while(done<2)
pthread_cond_wait(&cond,&m);
pthread_mutex_unlock(&m);
}
int main(int argc,char *argv[]){
a= atoi(argv[1]);
b= atoi(argv[2]);
c = atoi(argv[3]);
d = sqrt(b * b - 4 * a * c);
printf("parent:begin\n");
pthread_t p1,p2;
pthread_create(&p1,NULL,child1_add,NULL);
pthread_create(&p2,NULL,child2_sub,NULL);
thr_join();
if(d>=0)
printf("x1=%.4f, x2=%.4f\n", x1, x2);
else
printf("no answer!");
printf("parent:end\n");
return 0;
}
运行: