zoukankan      html  css  js  c++  java
  • 临界区访问的两个类:临界区类,共享临界区类

    CSharedCriticalSection 实现临界区的访问:加锁、去锁
    CSharedMutex 实现临时窃取临界区对象,然后加锁,对象销毁时又会去锁,然后归还对象

    class CSharedCriticalSection {
    public:
        CSharedCriticalSection() {
            InitializeCriticalSection(&critical_section_);
        }
    
        ~CSharedCriticalSection() {
            DeleteCriticalSection(&critical_section_);
        }
    
        void lock() {
            EnterCriticalSection(&critical_section_);
        }
    
        void unlock() {
            LeaveCriticalSection(&critical_section_);
        }
    
    private:
        CRITICAL_SECTION critical_section_;
    };
    
    
    class CSharedMutex {
    public:
        explicit CSharedMutex(CSharedCriticalSection& critical_section)
        : is_lock_(false)
        , critical_section_(critical_section)
        {
            if(is_lock_ == false) {
                is_lock_ = true;
                critical_section_.lock();
            }
        }
    
        ~CSharedMutex(){
            if(is_lock_) {
                is_lock_ = false;
                critical_section_.unlock();
            }
        }
    
        void lock() {
            if(is_lock_ == false) {
                is_lock_ = true;
                critical_section_.lock();
            }
        }
    
        void unlock() {
            if(is_lock_) {
                is_lock_ = false;
                critical_section_.unlock();
            }
        }
    
    protected:
        CSharedMutex(const CSharedMutex& rhs)
            : critical_section_(rhs.critical_section_)
        {
    
        }
    
        CSharedMutex& operator=(const CSharedMutex& rhs) {
            return *this;
        }
    
    private:
        volatile bool is_lock_;
        CSharedCriticalSection& critical_section_;
    };
  • 相关阅读:
    字符串匹配的三种算法
    字符串匹配
    多少个矩形被覆盖
    指针和地址的区别
    股票开盘的最大成交额-----一道不错的贪心算法题目
    Z字形扫描矩阵
    第几次出现
    节日(CCF试题)
    数字排序
    JS对象添加新的字段
  • 原文地址:https://www.cnblogs.com/eaglexmw/p/11242844.html
Copyright © 2011-2022 走看看