std::recursive_mutex

252 阅读1分钟

下面是一个示例,展示了如何在 C++ 中使用递归互斥锁(std::recursive_mutex):

#include <iostream>
#include <thread>
#include <mutex>

// 递归函数,使用递归互斥锁保护
void recursiveFunction(int depth, std::recursive_mutex& mtx) {
    // 对递归深度进行打印
    std::lock_guard<std::recursive_mutex> lock(mtx);
    std::cout << "Depth: " << depth << std::endl;

    if (depth > 0) {
        // 递归调用
        recursiveFunction(depth - 1, mtx);
    }
}

int main() {
    // 创建递归互斥锁
    std::recursive_mutex mtx;

    // 启动一个线程,调用递归函数
    std::thread t([&]() {
        recursiveFunction(5, mtx);
    });

    // 等待线程执行完成
    t.join();

    return 0;
}

在这个示例中,我们定义了一个递归函数 recursiveFunction,它会递归调用自身来打印深度信息。在每次调用时,会获取递归互斥锁 mtx 来保护对共享资源的访问。由于使用了递归互斥锁,同一个线程可以多次获取该锁,不会导致死锁。

main 函数中,我们创建了一个递归互斥锁 mtx,然后启动一个线程来调用递归函数。在调用函数时,线程会获取并释放递归互斥锁,确保了对共享资源的安全访问。