#include <stdio.h>
#include <pthread.h>
int a[100];
int nproc=3,N=10;
int barcount,over,count,total;
pthread_mutex_t lock,condlock;
pthread_cond_t co1,co2;
float average,final_dev;
void *work(void *arg);
main()
{
int bar,k,ctr,i,j;
pthread_t id;
void **p;
for(i=0;i<N;i++)
scanf("%d",a+i);
total=0;count=0;over=0;
final_dev=0.0;barcount=0;
pthread_mutex_init(&lock,NULL);
pthread_mutex_init(&condlock,NULL);
pthread_cond_init(&co1,NULL);
pthread_cond_init(&co2,NULL);
for(i=0;i<nproc;i++)
{
if(0==pthread_create(&id,NULL,work,(void *)i))
continue;
else
printf("Thread creation failure....\n");
}
pthread_mutex_lock(&condlock);
over=1;//printf("mainlock\n");if(0!=pthread_cond_broadcast(&co1))
printf("ERR1...\n");
pthread_mutex_unlock(&condlock);
while(barcount!=nproc) sleep(1);
count=0;average=total*1.0/N;
pthread_mutex_lock(&condlock);
barcount=0;
//printf("main lock");
pthread_cond_broadcast(&co2);
pthread_mutex_unlock(&condlock);
while(barcount!=nproc) sleep(1);
printf("The Total is %d\n",total);
printf("The Average is %f\n",average);
printf("The Standard devn is %f\n",final_dev);
}
void *work(void *arg)
{
int sum=0;
int i,id;float dev=0;void *stat;
pthread_mutex_lock(&condlock);
if(over==0)
{
// printf("lock\n");
pthread_cond_wait(&co1,&condlock);
// printf("unlock");
}
pthread_mutex_unlock(&condlock);
id=(int) arg;
// printf("thread id %d\n",pthread_self());while(1)
{
pthread_mutex_lock(&condlock);
i=count;count+=5;
pthread_mutex_unlock(&condlock);
if(i<N)
{
int bound;
bound=(N<i+5) ? N:i+5;
for(;i<bound;i++)
sum+=a[i];
sleep(1);
}
elsebreak;
}
pthread_mutex_lock(&condlock);
total+=sum;
pthread_mutex_unlock(&condlock);
// printf("%d did %d of %d \n",id,sum,total);
pthread_mutex_lock(&condlock);
barcount++;
if (barcount>0) pthread_cond_wait(&co2,&condlock);
pthread_mutex_unlock(&condlock);
while(1)
{
pthread_mutex_lock(&condlock);
i=count;count+=5;
pthread_mutex_unlock(&condlock);
if(i<N)
{
int bound;
bound=(N<i+5) ? N:i+5;
for(;i<bound;i++)
dev+=(average>a[i])?average-a[i]:a[i]-average;
sleep(1);
}
elsebreak;
}
pthread_mutex_lock(&condlock);
final_dev+=dev;
barcount++;
pthread_mutex_unlock(&condlock);
// printf("Therad %d did %f of %f\n",id,dev,final_dev);
pthread_exit(&stat);
}