2017-10-13 64 views
-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; 
} 
+1

我會避免使用諸如new int [N]之類的行,使用STL容器(如向量或列表) – rak007

+0

實際上,您的代碼中沒有任何問題。問題是什麼?? –

+0

我發佈1 我想用多線程杉計算皮的問題,但生病後再次 –

回答

0

問題1

您需要創建相同的方式n線程爲HelloCPP11(),並通過iPieEstimateAux()作爲線程排名變量。

使用線程排名變量在制定的開始和停止點環路(如start = rank * (n/# threads)stop = (rank + 1) * (n/# threads)和設置在for循環中for(int i = start; i < stop...){}

商店4 * sum陣列中的每個線程,總結他們在調用函數後t[x].join()

問題2

您需要使用此線程技術的功能拆分作爲唯一的真正障礙是t[x].join(),所以你必須用函數的pt1創建線程,加入它們,然後再用下一部分來完成。