对π的估计用的是Monte Carlo,使用多线程主要是使用循环建立多线程和使用互斥锁来保证子线程中对共享变量sum操作时,同一时间只有一个线程对其进行更改。
代码如下:
/**
* File: calcuPai.c
*
* Description:
* use gcc calcuPai.c -lpthread -o calcuPai to compile
* use ./calcuPai <the number of spots> <the number of threads> to execute
* use loops to create threads
*
* Date: 2023-11-25
* Verson 1.0.1
**/
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <pthread.h>
#include <math.h>
#include <time.h>
int sum;
bool available=true;
//mutex lock
void acquire()
{
while(!available){};
available=false;
}
void release()
{
available=true;
}
//thread function
void *runner(void *param)
{
int i,n=atoi(param),count=0;
float x,y;
srand(time(NULL));
for(i=0;i<n;i++)
{
x=(float)rand()*2/(float)(RAND_MAX)-1;
y=(float)rand()*2/(float)(RAND_MAX)-1;
if(x*x+y*y<=1) count++;
}
acquire();//get
sum+=count;
release();//put
}
int main(int argc,char* argv[])
{
float pai=0;
int i,thrd=atoi(argv[2]);
pthread_t tid[thrd]; //identifier
pthread_attr_t attr[thrd]; //attributes
//judge for erro
if (argc != 3)
{
fprintf(stderr,"usage: a.out <integer value> <integer value>\n");
return -1;
}
if (atoi(argv[1]) < 0)
{
fprintf(stderr,"Argument %d must be non-negative\n",atoi(argv[1]));
return -1;
}
for(i=0;i<thrd;i++)
{
pthread_attr_init(&attr[i]); //default
pthread_create(&tid[i],&attr[i],runner,argv[1]);
}
//wait for all children thread over
for(i=0;i<thrd;i++)
pthread_join(tid[i],NULL);
pai=sum*4.0/atoi(argv[1])/thrd;
printf("The value of Pai is aproximately %f\n",pai);
}