#include <stdio.h>
#include<stdlib.h>
#include <pthread.h>
#include <time.h>
#define N 500000
#define no_threads 10
int global_index=0;
int sum=0;
pthread_mutex_t mutex1;
void *slave(void *ignored)
{
int local_index,partial_sum=0;
double x,y;
do{
pthread_mutex_lock(&mutex1);
local_index=global_index;
global_index++;
pthread_mutex_unlock(&mutex1);
// sleep(0.00001);
if(local_index<N)
srand(time(NULL));
{x=(double)rand()/RAND_MAX;
y=(double)rand()/RAND_MAX;
if((x*x+y*y)<1)
partial_sum++;}
}while (local_index<N);
printf("partial_sum=%d\n",partial_sum);
pthread_mutex_lock(&mutex1);
sum+=partial_sum;
printf("sum=%d\n",sum);
pthread_mutex_unlock(&mutex1);
return;
}
main()
{
int i;
time_t start_time=0,end_time=0;
pthread_t thread[no_threads];
pthread_mutex_init(&mutex1,NULL);
start_time=time((time_t*)0);
for(i=0;i<no_threads;i++)
if(pthread_create(&thread[i],NULL,slave,NULL)!=0)
perror("Pthread_create fails");
for(i=0;i<no_threads;i++)
if(pthread_join(thread[i],NULL)!=0)
perror("Pthread_join fails");
printf("The pi is %f\n",(double)4*sum/N);
end_time=time((time_t *)0);
printf("time=%f\n",difftime(end_time,start_time));
}
看这段程序有什么毛病,为什么会运行的更慢了呢?