【muduo】避免使用无效的mutex

10 篇文章 1 订阅
文章介绍了Muduo库中EventLoop的runInLoop函数,如何避免不必要的mutex获取,通过测试对比,使用Muduo方式处理线程同步在性能上比盲目获取mutex提高了近一倍。
摘要由CSDN通过智能技术生成

在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损耗-CSDN博客

测试结果如下:
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

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值