实现:
#ifndef TG_RECURSIVE_LOCK_H
#define TG_RECURSIVE_LOCK_H
#include<thread>
#include<mutex>
class tg_recursive_lock
{
public:
tg_recursive_lock():_count(0)
{
}
~tg_recursive_lock()=default;
void lock()
{
if (_count == 0)
{
_mutex.lock();
_thread_id = std::this_thread::get_id();
_count++;
}
else if (std::this_thread::get_id() == _thread_id)
{
_count++;
}
else
{
_mutex.lock();
_thread_id = std::this_thread::get_id();
_count++;
}
}
void unlock()
{
if (_count > 0)
{
_count--;
}
if (_count == 0)
{
_mutex.unlock();
}
}
private:
int _count;
std::mutex _mutex;
std::thread::id _thread_id;
};
#endif