对于一个线程的两个操作,使用与不适用mutex性能差距将近一倍。
测试程序如下:
#include <mutex>
std::mutex mtx;
void setValue()
{
// std::lock_guard<std::mutex> guard(mtx);
fprintf(stdout, "setValue.\n");
}
void getValue()
{
// std::lock_guard<std::mutex> guard(mtx);
fprintf(stdout, "getValue.\n");
}
int main()
{
int count = 1000000000;
while(count-- > 0)
{
setValue();
getValue();
}
return 0;
}
编译选项使用了:-O0
在同一台机器上,执行结果如下:
// 使用mutex的结果
[@localhost mutex]$ time ./performance_mutex > /dev/null
real 1m17.147s
user 1m15.506s
sys 0m1.637s
// 不使用mutex的结果
[@localhost mutex]$ time ./performance_mutex > /dev/null
real 0m44.046s
user 0m42.480s
sys 0m1.565s
性能差距将近一倍
在多线程编程中,使用mutex进行资源互斥访问可以避免数据竞争,但会带来一定的性能开销。测试显示,对于一个简单的线程操作,在启用mutex保护和不启用的情况下,执行时间相差近一倍。这表明mutex虽然提供了线程安全,但可能导致执行效率降低。

7041

被折叠的 条评论
为什么被折叠?



