Pthread多线程计算圆周率(C++)

积分法

计算公式

在这里插入图片描述

串行代码

//
//  Created by HISS on 2020/11/5.
//  Copyright © 2020 HISS. All rights reserved.
//
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <unistd.h>
#include <iomanip>
#include <time.h>

using namespace std;

int main()
{
   
    struct timeval time1, time2;
	double ans = 0, N;
    cout << "输入n:" << endl;
    cin >> N;
    gettimeofday(&time1, NULL);
	for(double i = 0; i < N; i ++)
		ans += (4/(1 + ((i + 0.5)/N)*((i + 0.5)/N)))/N;
	cout << setprecision(20) << ans << endl;
    gettimeofday(&time2, NULL);
    printf("s: %ld, ms: %ld\n", time2.tv_sec-time1.tv_sec, (time2.tv_sec*1000 + time2.tv_sec/1000)-(time1.tv_sec*1000 + time1.tv_sec/1000));
}

并行代码

//
//  Created by HISS on 2020/11/5.
//  Copyright © 2020 HISS. All rights reserved.
//
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <unistd.h>
#include <iomanip>
#include <time.h>
#include <pthread.h>

using namespace std;

long long n;
int thread_count;
double sum = 0.0;
pthread_mutex_t mutex;

void* Thread_sum(void* rank)
{
   
    int my_rank = *(int *) rank;
    double my_sum = 0.0;
    long long i;
    long long my_n = n/thread_count;
    long long my_first_i = my_n * my_rank;
    long long my_last_i = my_first_i + my_n;
    
    for(i = my_first_i; i < my_last_i; i ++)
        my_sum += 4 / (1 + ((i + 0.5) / n )*((i + 0.5) / n )) / n;
    
    pthread_mutex_lock(&mutex);
    sum += my_sum;
    pthread_mutex_unlock
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值