有些场景中,我们需要让线程在同一互斥上多次重复加锁,而无需解锁。

下面是一个使用 std::recursive_mutex 的示例代码:

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

std::recursive_mutex mtx;

void func(int n) {
    mtx.lock();
    std::cout << "Thread " << n << " locked the mutex" << std::endl;
    if (n > 1) {
        func(n - 1);
    }
    std::cout << "Thread " << n << " unlocked the mutex" << std::endl;
    mtx.unlock();
}

int main() {
    std::thread t1(func, 3);
    std::thread t2(func, 2);
    t1.join();
    t2.join();
    return 0;
}

C:\Users\hanhandi\CLionProjects\untitled\cmake-build-debug\untitled.exe
Thread 3 locked the mutex
Thread 2 locked the mutex
Thread 1 locked the mutex
Thread 1 unlocked the mutex
Thread 2 unlocked the mutex
Thread 3 unlocked the mutex
Thread 2 locked the mutex
Thread 1 locked the mutex
Thread 1 unlocked the mutex
Thread 2 unlocked the mutex

进程已结束,退出代码0

在这个示例代码中,我们定义了一个递归函数 func,它会递归地调用自己,直到 n 的值为 1。在每次调用 func 时,线程会先锁定 std::recursive_mutex 对象 mtx,然后输出一条信息表示线程已经锁定了互斥量。如果 n 的值大于 1,线程会递归地调用 func,直到 n 的值为 1。最后,线程会输出一条信息表示线程已经释放了互斥量,并解锁 std::recursive_mutex 对象 mtx。

需要注意的是,std::recursive_mutex 是一个递归互斥量,它允许同一个线程多次对它进行加锁操作,而不会导致死锁。在使用 std::recursive_mutex 时,需要注意避免死锁和竞争条件的问题。