使用忙等待计算ln2值的Pthreads程序
#include"stdio.h"
#include"stdlib.h"
#include"pthread.h"
#define NUM_THREADS 8
long int thread_count;
pthread_mutex_t mutex;
long int n = 10000000;
double ln2=0.0;
long int flag = 0;
void *Compute_ln2(void *rank);
int main(int argc ,char * argv[])
{
long int thread;
pthread_t thread_handle[NUM_THREADS];
thread_count = NUM_THREADS;
pthread_mutex_init(&mutex, NULL);
for (thread = 0;thread < thread_count;thread++)
{
pthread_create(&thread_handles[thread],NULL,Compute_ln2,(void *)thread);
}
for (thread = 0;thread < thread_count;thread++)
{
pthread_join(thread_handles[thread], NULL);
}
printf("Approximation of pi%15.13f\n", ln2);
}
void * Compute_ln2(void * rank)
{
long int my_rank=(long int)rank;
double factor;
double my_ln2 = 0.0;
long int i;
long int my_n=n/thread_count;
long int my_first_i = my_n * my_rank;
long int my_last_i = my_first_i + my_n;
if(my_first_i%2==0)
factor = 1.0;
else
factor = -1.0;
for (i = my_first_i;i < my_last_i;i++,factor=-factor)
{
my_ln2+=factor/(i+1)
}
while(flag!=my_rank)
ln2+=my_ln2;
flag = (flag + 1) % thread_count;
return NULL;
}
在Linux系统中端该.c文件所在文件夹下打开终端,输入以下命令进行编译运行: