gpt4 book ai didi

c++ - 提升条件互斥体性能不佳

转载 作者:行者123 更新时间:2023-11-28 07:59:04 25 4
gpt4 key购买 nike

我是使用条件变量的新手,所以我很容易在这里做一些愚蠢的事情,但是当我使用增强线程而不是直接调用函数时,我得到了一些奇怪的性能。如果我将在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com