C++与Boost的并发性

Concurrency in C++ with Boost

本文关键字:并发 Boost C++      更新时间:2023-10-16

我在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();

然而,这将运行两个线程,每个线程将迭代十亿次,对吧?我想要两个线程同时完成这项工作,这样整个工作就会运行得更快。我不在乎关于sync,它只是一个速度测试。

谢谢!

可能有更好的方法,但这应该有效,它将变量的范围传递到线程中进行迭代,它还在线程启动前启动一个计时器,并在两个线程都完成后在计时器之后结束。应该很清楚如何将其扩展到更多线程。

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;