多线程之谜与 Boost C++
Multithreading mystery in C++ with Boost
static void testlock()
{
for(int i=0;i<10000000;i++)
{
float f=2.0/i;
}
}
static void TEST()
{
cout<<"Start testing" <<endl;
unsigned int startClock;
for(int i=1;i<=10;i++)
{
startClock = clock();
vector<boost::thread*> threads;
for(int j=0;j<i;j++)
threads.push_back(new boost::thread(&testlock));
for(int j=0;j<i;j++)
{
threads[j]->join();
delete threads[j];
}
cout << i << " threads: "<< clock()-startClock << endl;
}
}
输出:
Start testing
1 threads: 180000
2 threads: 350000
3 threads: 540000
4 threads: 730000
5 threads: 900000
6 threads: 1080000
7 threads: 1260000
8 threads: 1510000
9 threads: 1660000
10 threads: 1810000
我在四核 PC(Core2Quad,4 核无超线程)上运行此代码,因此我预计 1-4 个线程需要大约相同的时间。相反,似乎只使用了一个内核。我在这里错过了什么?
谢谢
更新:
- 我在 Ubuntu Linux 下使用 Eclipse CDT
-我用 Pthread 尝试了相同的方法,但得到了相同的结果
我的一位同事找到了解决方案:clock() 测量 CPU 周期,因此如果两个线程正在运行,它的运行速度会提高一倍。与gettimeofday的计时给出了预期的结果。
首先,(抱歉,正如 Igor 在评论中正确指出的那样,它对浮点运算有效,在这种情况下,它会导致 +无穷大。i=0
2.0/i
除以零
Seconly,即使你修复了这个问题,你的testlock
函数也可能会被优化为零,因为结果永远不会被使用。
因此,目前您只是在衡量创建和连接线程的开销,这就是线性增加的原因。
相关文章:
- 理解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问题
- C++:如何在CLion IDE中安装Boost
- C++Boost Asio Pool线程,带有lambda函数和传递引用变量
- 如何在boost beast http请求中设置http头
- Boost Spirit,获取迭代器内部语义动作
- boost::asio::steady_timer()与sleep()我应该使用哪一个
- boost::asio如何生成多个协同程序,然后加入它们
- 当我尝试使用 sstream 和分面将 Boost Time_duration转换为字符串时,我没有得到所需的格式
- Visual Studio(或任何其他工具)能否将地址解释为调用堆栈(boost上下文)的开头
- 如何使用boost::具有嵌套结构和最小代码更改的序列化
- 使用Boost Interprocess创建托管共享内存需要很长时间
- Boost::posix_time::ptime舍入到给定的分钟数
- boost xml parsingl将xml的路径作为变量发送