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陷入内核的次数更少。

相关推荐
思麟呀11 分钟前
C++11并发编程:call_once一次性执行+atomic原子类型+CAS无锁编程+自旋锁
linux·开发语言·jvm·c++·windows
Lumbrologist30 分钟前
【C++】零基础入门 · 第 13 节:类与对象基础
java·c++·算法
古道青阳42 分钟前
深入密码学内核:对称/非对称原理、PKI体系及C语言实现
网络协议·https·ssl
吴可可1232 小时前
CAD2004自定义实体开发环境配置
c++·算法
L_09072 小时前
【C++】C++11 新特性
开发语言·c++
Fanfanaas2 小时前
C++ 继承
java·开发语言·jvm·c++·学习·算法
十五年专注C++开发3 小时前
cereal 库:C++ 序列化的轻量之选
开发语言·c++·序列化·反序列化·cereal
lqqjuly3 小时前
设计模式:理论、架构与 C++ 实现—SOLID原则到23 种经典模式
c++·设计模式·架构
BestOrNothing_20153 小时前
C++零基础到工程实战(5.2.8)多文件声明定义函数和全局变量
c++·c++多文件编译·.h头文件·.cpp·函数声明定义
星卯教育tony3 小时前
2026年全国青少年信息素养大赛主题应用 数字守艺人 丝路新城 星火征程 智传民韵 c++ python scratch 所有真题免费分享
开发语言·c++