会计考友 发表于 2012-8-4 12:07:07

Linux认证之linuxC互斥线程池-条件变量

Linux认证之linuxC互斥线程池-条件变量
linuxC互斥线程池-条件变量
C代码
#include 《pthread.h》
#include 《bits/pthreadtypes.h》
#include 《stdio.h》
#include 《stdlib.h》
#define MAXS 1000
#define MAXTDS 5 //线程池大小
double myjg[MAXS+1];//计算结果存放位置
int max;
pthread_mutex_t mylock,eventlock;
pthread_cond_t myevent;
pthread_t threads[MAXTDS+2]; //线程池,完成1/n计算
int isend=0;
void *mycomp(void *x){//计算1/i的结果,计算结果放在一个数组中。
int i=0;
while (1){
pthread_mutex_lock(&mylock);
if (myjg[0]《max){myjg[0]++;}
i=myjg[0];//myjg[0]存放着线程已经计算到的i。
pthread_mutex_unlock(&mylock);
if (!isend){
myjg[i]=(1/(double)i);
printf(“1/%d finished,push %.10f\n”,i,myjg[i]);
pthread_cond_broadcast(&myevent);//广播信号,多个任务不被阻塞,多个任务竞争互斥锁的所有权。也可以使用pthread_cond_signal(&event);发送信号,这样只有一个线程不被阻塞,其它线程都被阻塞。
}
if (i》=max){//计算完毕,退出线程
isend=1; //深未来技术http://deepfuture.javaeye.com/
break;
}
}
}
void *myprint1(void *xx){//读取数组,将计算结果累加,最终完成1/1+1/2+1/3+.。..。.+1/n的计算
int maxi;
int curi=1;
double jg=0;
while(curi《=max)
{
pthread_mutex_lock(&eventlock);//用于条件变量的互斥,条件变量就是一个用来发送事件发生信号的信号量
pthread_cond_wait(&myevent,&eventlock);//等待条件变量发生。条件变量必须与一个互斥锁相关联
pthread_mutex_unlock(&eventlock);
pthread_mutex_lock(&mylock); //读取当前计算的进度
maxi=myjg[0];
pthread_mutex_unlock(&mylock);
for (;curi《=maxi;curi++){
jg+=myjg[curi];
printf(“1/%d:%.10f added result %.10f\n”,curi,myjg[curi],jg);
}
}

printf(“================add finish!============ result:%.10f\n”,jg);//输出累加结果。
}
void *myprint2(void *xx){//读取数组,将计算结果完成1/1+1/2-1/3+1/4-1/5.。..。.的计算
int maxi;
int curi=1;
double jg=0;
int fh=1;
while(curi《=max)
{
pthread_mutex_lock(&eventlock);//用于条件变量的互斥,条件变量就是一个用来发送事件发生信号的信号量
pthread_cond_wait(&myevent,&eventlock);//等待条件变量发生。条件变量必须与一个互斥锁相关联
pthread_mutex_unlock(&eventlock);
pthread_mutex_lock(&mylock); //读取当前计算的进度
maxi=myjg[0];
pthread_mutex_unlock(&mylock);
for (;curi《=maxi;curi++){
jg+=fh*myjg[curi];
printf(“*******1/%d:%.10f computed result %.10f\n”,curi,myjg[curi],jg);
fh=-fh;
}
}
printf(“================compute finish!============ result:%.10f\n”,jg);//输出累加结果
}
int main(){
//计算1+1/2+1/3+.。..。.和1+1/2-1/3+1/4-1/5.。..。.
pthread_mutex_init(&mylock,NULL);
pthread_mutex_init(&eventlock,NULL);
pthread_cond_init(&myevent,NULL);
printf(“please input an integer:(《=%d)”,MAXS);
while (scanf(“%d”,&max),max》MAXS){//n的最大值
printf(“please input an integer:(《=%d)”,MAXS);
};
//深未来技术http://deepfuture.javaeye.com/
myjg[0]=0;
pthread_create(&(threads[0]),NULL,myprint1,NULL);
pthread_create(&(threads[1]),NULL,myprint2,NULL);
for (int i=2;i《=MAXTDS;i++){
pthread_create(&(threads[i]),NULL,mycomp,NULL);
sleep(1);
}
sleep(1);
return(0);
页: [1]
查看完整版本: Linux认证之linuxC互斥线程池-条件变量