递归锁的实现与使用

实现:

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

使用:

#include <iostream>
#include <memory.h>
#include <string.h>
#include"tg_recursive_lock.h"

tg_recursive_lock g_recursive_lock;

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

    return 0;
}

猜你喜欢

转载自blog.csdn.net/f110300641/article/details/84455251
今日推荐