作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我是使用条件变量的新手,所以我很容易在这里做一些愚蠢的事情,但是当我使用增强线程而不是直接调用函数时,我得到了一些奇怪的性能。如果我将在 func 上创建 boost 线程的行更改为直接调用 func,代码将运行几个命令更快。我已经尝试使用 source forge 的 boost threadpool 软件,但没有任何区别......
代码如下:
#include <boost/thread.hpp>
using namespace boost;
condition_variable cond;
mutex conditionalMutex;
int numThreadsCompleted = 0;
int numActiveThreads = 0;
void func()
{
{
lock_guard<mutex> lock(conditionalMutex);
--numActiveThreads;
numThreadsCompleted++;
}
cond.notify_one();
};
int main()
{
int i=0;
while (i < 100000)
{
if (numActiveThreads == 0)
{
++numActiveThreads;
thread thd(func);
//Replace above with a direct call to func for several orders of magnitude
//performance increase...
++i;
}
else
{
unique_lock<mutex> lock(conditionalMutex);
while (numThreadsCompleted == 0)
{
cond.wait(lock);
}
numThreadsCompleted--;
}
}
return 0;
}
最佳答案
性能肯定比直接调用函数差很多。您启动一个线程,然后等待该线程结束。即使您将启动线程的开销减少到零,您也可以与该线程通信。而且您将至少有一个上下文切换,并且由于您的 func() 基本上什么都不做,因此开销成为一个重要因素。在 func() 中添加更多的有效负载,比率将会改变。如果要做的事情很少,就在发现这个事情的线程上做。
顺便说一句:你有一个竞争条件,因为你在没有锁定互斥锁的情况下写入 numActiveThreads。上面的代码归结为:
int main()
{
int i=0;
while (i < 100000)
{
thread thd(func);
thd.join();
++i;
}
return 0;
}
而且确实没有理由认为这应该比:
int main()
{
int i=0;
while (i < 100000)
{
func();
++i;
}
return 0;
}
关于c++ - 提升条件互斥体性能不佳,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11979454/
我是一名优秀的程序员,十分优秀!