在Linux下用多线程估计π的值

        对π的估计用的是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);
	
}

 

 

 

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值