ble jg=0;
int fh=1;
int rc;
while(curi<=max)
{
maxi=0;
sleep(2);
pthread_mutex_lock(&eventlock);//用于条件变量的互斥,条件变量就是一个用来发送事件发生信号的信号量
rc=pthread_cond_wait(&myevent,&eventlock);//在等待条件变量myevent的发生。条件变量必须与一个互斥锁eventlock相关联,条件变量不提供锁定,必须有一个互斥锁eventlock配合。
//互斥锁eventlock在调用wait前应锁定,然后在wait期间,互斥量eventlock被解锁。挂起线程执行,直到条件变量myevent收到信号
// myhaspl
if (rc==0){
maxi=myjg[0];
fflush(stdout);
pthread_mutex_unlock(&eventlock);
while (curi<=maxi){
jg+=fh*myjg[curi];
printf("*******1/%d:%.10f computed result %.10f\n",curi,myjg[curi],jg);
fflush(stdout);
fh=-fh;
curi++;
}
printf("===============compute finish!=========== result:%.10f\n",jg);//输出累加结果
fflush(stdout);
}
else{//error
perror("pthread_cond_wait");
fflush(stdout);
pthread_mutex_unlock(&eventlock);
continue;
}
}
pthread_exit(NULL);
}
int main(){
//计算1+1/2+1/3+......和1+1/2-1/3+1/4-1/5......
pthread_mutex_init(&eventlock,NULL);
pthread_cond_init(&myevent,NULL);
int i =0;
printf("please input an integer:(<=%d)",MAXS);
while (scanf("%d",&max),max>MAXS){//n的最大值
printf("please input an integer:(<=%d)",MAXS);
};
//myhaspl
myjg[0]=0;
pthread_create(&(threads[i]),NULL,myprint1,(void *)&i);
sleep(1);
i++;
pthread_create(&(threads[i]),NULL,myprint2,(void *)&i);
sleep(1);
i++;
for (;i<=MAXTDS;i++){
pthread_create(&(threads[i]),NULL,mycomp,(void *)&i);
sleep(1);
}
sleep(MAXTDS*2*(i/10+1)); //wait......
pthread_mutex_destroy(&eventlock);
return(0);
}
|