递归锁的实现与使用

实现:

#ifndef TG_RECURSIVE_LOCK_H
#define TG_RECURSIVE_LOCK_H

#include
#include

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 // TG_RECURSIVE_LOCK_H

使用:

#include 
#include 
#include 
#include"tg_recursive_lock.h"

tg_recursive_lock g_recursive_lock;

int main()
{
    std::lock_guard ll(g_recursive_lock);
    {
        std::lock_guard ll(g_recursive_lock);
        {
            std::lock_guard ll(g_recursive_lock);
        }
    }

    return 0;
}

 

你可能感兴趣的:(C++11)