在muduo源码EventLoop.h中,提供了void runInLoop(Functor cb);
// 通过该接口输入的任务,如果调用的loop线程,直接执行任务;否则,放入队列中等待运行
void EventLoop::runInLoop(Functor cb)
{
if (isInLoopThread())
{
cb();
}
else
{
queueInLoop(std::move(cb));
}
}
巧妙地避免获取没有必要的mutex。
获取mutex的使用权也是相当耗费性能的。
通过写测试程序,利用muduo的方式避免获取无效的mutex,与盲目获取mutex,在性能上差距将近1倍
模仿muduo方式测试程序
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/syscall.h>
#include <sys/types.h>
__thread int t_main_tid = 0;
__thread int t_cachedTid = 0;
void updateCacheid()
{
if (t_cachedTid == 0)
{
t_cachedTid = syscall(SYS_gettid);
}
}
int current_tid()
{
if (__builtin_expect(t_cachedTid == 0, 0))
{
updateCacheid();
}
return t_cachedTid;
}
void setValue()
{
if (t_main_tid == current_tid())
{
fprintf(stdout, "setValue.\n");
}
}
void getValue()
{
if (t_main_tid == current_tid())
{
fprintf(stdout, "getValue.\n");
}
}
int main()
{
t_main_tid = syscall(SYS_gettid);
printf("main_tid:%d\n", t_main_tid);
int count = 1000000000;
while(count-- > 0)
{
setValue();
getValue();
}
return 0;
}
盲目使用mutex测试程序参考:
std::mutex影响性能_std::mutex损耗-优快云博客
测试结果如下:
performance_mutex(盲目使用mutex)
gettid_avoid_mutex(使用muduo的方式,避免盲目使用)
$ time ./performance_mutex > /dev/null
real 0m56.497s
user 0m56.080s
sys 0m0.410s
$ time ./gettid_avoid_mutex > /dev/null
real 0m32.657s
user 0m32.251s
sys 0m0.400s
$ time ./performance_mutex > /dev/null
real 0m57.836s
user 0m57.481s
sys 0m0.350s
$ time ./gettid_avoid_mutex > /dev/null
real 0m33.027s
user 0m32.733s
sys 0m0.290s
$ time ./performance_mutex > /dev/null
real 0m57.432s
user 0m57.095s
sys 0m0.330s