访问std :: recursive_mutex使用的所有者计数器

Access the owners counter used by std::recursive_mutex

本文关键字:所有者 计数器 mutex std recursive 访问      更新时间:2023-10-16

我有一个算法的决定基于共享std::recursive_mutex的深度。

#include <iostream>
#include <mutex>
#include <thread>
int g_i = 0;
std::recursive_mutex g_i_mutex;
void bar() {
  std::lock_guard<std::recursive_mutex> lock(g_i_mutex);
  switch (get_counter(g_i_mutex)) { // some way to find the number of owners
    case 1: std::cout << "depth 1n"; break;
    case 2: std::cout << "depth 2n"; break;
    default:;
  }
}
void foo() {
   std::lock_guard<std::recursive_mutex> lock(g_i_mutex);
   std::cout << "hellon";
   bar();
}
int main() {
  foo(); //print hello then depth 2
  bar(); //print depth 1
}

我已经阅读了递归静音的使用计数,并且在每次锁定/解锁的调用中,它们都会增加和减少它,有没有办法访问该信息?

不,你不能。

这是不可能的,因为您提到的计数器是实现解决方案,它可能存在也可能不存在。如果您知道标准库的特定实现使用了计数器,则可以使用一些魔术(指针算术和铸件)来获得它,但这将是不确定的行为。

话虽如此,没有什么禁止您定义自己的recursive_mutex

#include <iostream>
#include <mutex>
#include <atomic>
class recursive_mutex
{
    std::recursive_mutex _mutex;
    std::atomic<unsigned> _counter;
public:
    recursive_mutex() : _mutex(), _counter(0) {}
    recursive_mutex(recursive_mutex&) = delete;
    void operator=(recursive_mutex&) = delete;
    void lock() { _mutex.lock(); ++_counter; }
    bool try_lock() { bool result = _mutex.try_lock(); _counter += result; return result; }
    void unlock() { --_counter; _mutex.unlock(); }
    unsigned counter() { return _counter; }
};
int main() {
  recursive_mutex m;
  m.lock();
  m.lock();
  std::cout << m.counter() << "n";
  m.unlock();
  std::cout << m.counter() << "n";
  m.unlock();
}

2
1

demo