C++与Boost的并发性
Concurrency in C++ with Boost
我在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;
相关文章:
- 理解boost::asio-async_read在无需读取内容时的行为
- boost::进程间消息队列引发错误
- 如何运行位于boost/libs/python/example/tutorial目录中的hello.cpp和Jamfil
- cmake如何在fedora工作站中找到boost静态库包
- CMake项目Boost库错误:Boost/config/compiler/gcc.hpp:165:10:致命错误:cs
- Boost Graph Library,修复节点大小
- 什么是"#include <boost/functional/hash.hpp> "?
- 基于boost的程序的静态链接——zlib问题
- 两个并发的 Python 进程可以在 Boost Python 中运行吗?
- 与 Boost.Asio 同步和并发的数据结构模式
- 正在从并发析构函数停止boost::asio::io_service::run()
- 使用Boost的半并发ICMP ping.Asio在Windows上
- 为什么这个使用boost的并发Hasmap不起作用
- Boost 并发库在使用 GNU C++ / LLVM C++ 编译时的行为不同
- C++与Boost的并发性
- boost::filesystem、std::getenv和并发性
- c++ Boost线程.如何使用递归尝试锁?死锁发生在并发代码中
- 是否可以使用boost构建并发进程间消息队列
- 使用Boost 1.55线程和文件系统并发内存损坏(Visual Studio 2013)
- 从boost无序到tbb并发哈希映射的转换