2012-02-21 97 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