访问std :: recursive_mutex使用的所有者计数器
Access the owners counter used by std::recursive_mutex
我有一个算法的决定基于共享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
相关文章:
- 循环在计数器中不起作用
- python集合的C++等价物是什么.计数器
- Python 集合.计数器,如何避免重复查找
- 请解释字谜的代码,我看不懂计数器数组,每个值已经是0
- C++ 警告:将新创建的 gsl::owner<> 分配给非所有者
- 堆分配的对象是否存在永不为空的唯一所有者?
- std::shared_ptr 自定义参考计数器
- 英特尔 TBB 程序不会终止,可能会误用参考计数器
- 不正确的比较和交换计数器输出用于快速排序功能
- OpenSSL API,使用GCM(伽罗瓦计数器模式)进行AES加密
- C++ 在循环中添加计数器变量并再次初始化其值
- 允许多个互斥锁所有者或指定数量的并发代码执行
- TgBot找不到所有者禁令权力
- 需要帮助才能在C++中创建类计数器
- 漂亮的计数器习语的错误或格式错误的静态订单惨败?
- 几乎总是自动和带计数器的循环
- 线程使用计数器C++
- 为什么使用 2 个嵌套循环 O(n^2) 复杂度来解决二和问题,当只改变循环计数器逻辑时运行得更快?
- 对于循环计数器不递增
- 访问std :: recursive_mutex使用的所有者计数器