C++ 我遇到了一个关于多线程的小问题。需要多线程来计算Pi和方差
问题1 我想使用多线程fir计算Pi,但首先我尝试在每个线程之间分割作业 问题2 下面还有一段代码,用于计算值数组的样本方差。我还想在代码的这一部分使用多线程。该算法需要对数据进行两次传递,因此需要某种同步(在这种情况下是一个障碍)C++ 我遇到了一个关于多线程的小问题。需要多线程来计算Pi和方差,c++,multithreading,C++,Multithreading,问题1 我想使用多线程fir计算Pi,但首先我尝试在每个线程之间分割作业 问题2 下面还有一段代码,用于计算值数组的样本方差。我还想在代码的这一部分使用多线程。该算法需要对数据进行两次传递,因此需要某种同步(在这种情况下是一个障碍) //LabClass.cpp:定义控制台应用程序的入口点。 // #包括“stdafx.h” #包括 #包括 #包括 #包括“Chrono.h” //当性能至关重要时,nbThreads应该是支持的硬件线程数 #定义NB_线程4 #定义N 10000 整数计数器;
//LabClass.cpp:定义控制台应用程序的入口点。
//
#包括“stdafx.h”
#包括
#包括
#包括
#包括“Chrono.h”
//当性能至关重要时,nbThreads应该是支持的硬件线程数
#定义NB_线程4
#定义N 10000
整数计数器;
void HelloWorld(int-id)
{
printf(“来自%d\n的Hello world”,id);
}
void HelloCPP11()
{
标准:螺纹t[NB_螺纹];
//发射
对于(int i=0;i 对于(int i=0;i问题1
您需要以与HelloCPP11()
相同的方式创建n
线程,并将i
传递给piestimateaux()
作为线程排名变量
使用thread ranking变量计算for循环中的开始点和停止点(例如start=rank*(n/#threads)
和stop=(rank+1)*(n/#threads)
并将for循环设置为for(int i=start;i
将4*sum
存储在每个线程的数组中,并在t[x]之后的调用函数中对其求和
问题2
您需要拆分函数,因为使用此线程技术的唯一真正障碍是t[x].join()
,因此您必须使用函数的pt1创建线程,将它们连接起来,然后在下一部分中再次执行该操作。我将避免使用诸如new int[N]之类的行,使用向量或列表之类的STL容器实际上代码中没有问题。问题是什么?我发布了问题,但我将再次发布问题1我想使用多线程fir计算Pi,但首先我尝试将作业拆分为每个线程问题2下面还有一段代码,用于计算样本变量C我还想在代码的这一部分使用多线程。算法需要对数据进行两次传递,因此需要某种类型的同步(在这种情况下是一个障碍)。
// LabClass.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <process.h>
#include <thread>
#include "Chrono.h"
//When performance is crucial, nbThreads should be the number of hardware threads supported
#define NB_THREADS 4
#define N 10000
int counter;
void HelloWorld(int id)
{
printf("Hello world from %d\n",id);
}
void HelloCPP11()
{
std::thread t[NB_THREADS];
//Launch
for (int i = 0; i < NB_THREADS; i++)
t[i] = std::thread(HelloWorld, i);
//Join
for (int i = 0; i < NB_THREADS; i++) {
t[i].join();
}
}
double PIEstimateAux(int n)
{
double sum=1;
double div=3.;
for (int i=0;i<n;i+=2)
{
sum=sum-1/div+1/(div+2);
div+=4;
}
return 4*sum;
}
void PIEstimate()
{
Chrono c;
double val=PIEstimateAux(N);
c.PrintElapsedTime_us("\nTime Pi (micro sec):");
std::cout << "\nPI estimate: " << val << "\n\n";
}
double SampleVarianceAux(int *t, int n)
{
double average=0;
double variance=0;
for (int i=0;i<n;i++)
average+=t[i];
average=average/(double) n;
for (int i=0;i<n;i++)
variance+=(t[i]-average)*(t[i]-average);
variance/=(n-1.);
return variance;
}
void SampleVariance()
{
//creating array of random numbers
int *t=new int[N];
if (t==NULL)
return ;
for (int i=0;i<N;i++)
t[i]=std::rand()%100;
Chrono c;
double val = SampleVarianceAux(t,N);
c.PrintElapsedTime_us("Variance time (micro sec):");
std::cout << "\nVariance estimate: " << val << "\n\n";
delete[] t;
}
int _tmain(int argc, _TCHAR* argv[])
{
printf("\t\t\tSimple Hello world call\n");
HelloWorld(0);
HelloCPP11();
PIEstimate();
SampleVariance();
return 0;
}