rpc:测试std::mutex 和 futex封装的FastPthreadMutex

FastPthreadMutex

cpp 复制代码
class FastPthreadMutex {
public:
    FastPthreadMutex() : _futex(0) {}
    ~FastPthreadMutex() {}
    void lock();
    void unlock();
    bool try_lock();
private:
    DISALLOW_COPY_AND_ASSIGN(FastPthreadMutex);
    int lock_contended();
    unsigned _futex;
};
#else
typedef butil::Mutex FastPthreadMutex;
#endif
}

FastPthreadMutex在是对futex的封装,在保证互斥的条件下使得线程间切换次数更少,以提高系统性能。

与mutex 在lock unlock的耗时测试

首先测试单线程 lock unlock的基准测试:

cpp 复制代码
#include "bthread/mutex.h"
#include <chrono>
#include <thread>
#include <iostream>
#include <cassert>
#include <vector>

// 对比FastPthreadMutex 和 std::mutex 的性能差距
bthread::internal::FastPthreadMutex waiter_lock{};
std::mutex std_mutex;
constexpr static int N = 10000000;
int cnt = 0;

void test1() {
    for(int i = 0; i < N; i++) {
        std_mutex.lock();
        ++cnt;
        std_mutex.unlock();
    }
}
void test2() {
    for(int i = 0; i < N; i++) {
        waiter_lock.lock();
        ++cnt;
        waiter_lock.unlock();
    }
}
int main() {
    // 统计耗时
    auto start = std::chrono::steady_clock::now();
    int n = 1;
    std::vector<std::thread> nums(n);
    for(int i = 0; i < n; i++) {
        nums[i] = std::thread(test1);
    }
    for(int i = 0; i < n; i++) {
        nums[i].join();
    }
    auto end = std::chrono::steady_clock::now();

    assert(cnt == n * N);
    std::cout << "std::mutex cost: " << std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count() << "ms" << std::endl;


    cnt = 0;
    start = std::chrono::steady_clock::now();
    
    for(int i = 0; i < n; i++) {
        nums[i] = std::thread(test2);
    }
    for(int i = 0; i < n; i++) {
        nums[i].join();
    }
    end = std::chrono::steady_clock::now();

    assert(cnt == n * N);
    std::cout << "FastPthreadMutex cost: " << std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count() << "ms" << std::endl;

}

当n = 1, 可以看到,在完全没有竞争的场景下,FastPthreadMutex的性能要比mutex强上一些

当n = 2时:

两个线程来回lock unlock的场景下,其性能表现波动较大,完全取决于OS当时的调度策略。

当n=4时:

FastPthreadMutex的表现明显强过std::mutex,因为FastPthreadMutex陷入内核的次数更少。

相关推荐
cjhbachelor2 分钟前
c++继承
c++
肩上风骋28 分钟前
C++14特性
开发语言·c++·c++14特性
IT大白鼠1 小时前
RSTP协议原理与配置详解:快速生成树技术的深度解析
网络·网络协议
QiLinkOS3 小时前
【从实验室到商业战场:发明专利如何重塑科技与企业的共生生态】
大数据·c语言·数据结构·c++·人工智能·单片机·算法
Irissgwe4 小时前
c++11(lambda表达式与包装器、线程库)
c++·c++11·lambda表达式·线程库·包装器·互斥量库·条件变量库
Peter·Pan爱编程5 小时前
14. Lambda 表达式:随手可写的函数对象
c++·算法·ai编程
笨鸟飞不快5 小时前
从一次网络请求出发,彻底搞懂事件循环、I/O 多路复用与响应式编程
网络协议
不想写代码的星星5 小时前
从分支预测角度看 C++:为什么你的热循环慢得离谱?
c++
郝学胜-神的一滴6 小时前
Qt 高级开发 018:复刻经典登录界面布局与窗口美化全解析
开发语言·c++·qt·程序人生·用户界面