2012-02-21 114 views
0

我在C++中一個很簡單的功能:併發在C++與升壓

double testSpeed() 
{ 
    using namespace boost; 
    int temp = 0; 

    timer aTimer; 
    //1 billion iterations. 
    for(int i = 0; i < 1000000000; i++) { 
     temp = temp + i; 
    } 
    double elapsedSec = aTimer.elapsed(); 
    double speed = 1.0/elapsedSec; 

    return speed; 
} 

我想運行多線程這個功能。我看到的例子是在線如下,我可以 做到這一點:

// start two new threads that calls the "hello_world" function 
    boost::thread my_thread1(&testSpeed); 
    boost::thread my_thread2(&testSpeed); 

    // wait for both threads to finish 
    my_thread1.join(); 
    my_thread2.join(); 

然而,這將運行兩個線程,每個將遍歷十億倍,對不對?我想讓兩個線程同時完成這項工作,這樣整個事情就會運行得更快。我不在乎 關於同步,它只是一個速度測試。

謝謝!

+1

如果你想共享數據,你必須同步 – littleadv 2012-02-21 05:30:42

回答

3

可能有更好的方法,但它應該工作,它傳遞變量的範圍以迭代到線程中,它還在線程啓動之前啓動單個計時器,並在計時器之後結束都完成了。這應該是非常明顯的如何擴展到更多的線程。

void testSpeed(int start, int end) 
{ 
    int temp = 0; 
    for(int i = start; i < end; i++) 
    { 
    temp = temp + i; 
    } 
} 


using namespace boost; 

timer aTimer; 

// start two new threads that calls the "hello_world" function 

boost::thread my_thread1(&testSpeed,   0, 500000000); 
boost::thread my_thread2(&testSpeed, 500000000, 1000000000); 

// wait for both threads to finish 
my_thread1.join(); 
my_thread2.join(); 

double elapsedSec = aTimer.elapsed(); 
double speed = 1.0/elapsedSec; 
+0

這確實是我在找的東西!非常感謝!! – user247866 2012-02-21 05:37:10