-1
問題1我遇到了一個關於多線程的小問題。需要多線程計算Pi和對差異
我想用多線程杉計算皮,但首先我試圖在每個線程
問題2
工作拆分那裏還有一段代碼,用於計算值數組的樣本方差。我也想在這部分代碼上使用多線程。該算法需要兩次數據傳遞,因此需要進行某種同步(在這種情況下是障礙)。
// 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;
}
我會避免使用諸如new int [N]之類的行,使用STL容器(如向量或列表) – rak007
實際上,您的代碼中沒有任何問題。問題是什麼?? –
我發佈1 我想用多線程杉計算皮的問題,但生病後再次 –