zoukankan      html  css  js  c++  java
  • C++之对同步对象进行封装包装

      包装器外观模式:把现有的非面向对象/面向对象API提供的函数和数据(例如底层操作系统API、基础类)封装在更加简洁使用的、健壮的、可维护的和聚合的面向对象的类接口之内,如线程同步对象的包装;

    #ifdef LINUX_PTHREADS
    #include <pthread.h>
    #include <semaphore.h>
    #define MUTEX_PTR_DECLARE pthread_mutex_t*
    #define MUTEX_LOCK(mutex) pthread_mutex_lock(mutex)
    #define MUTEX_UNLOCK(mutex) pthread_mutex_unlock(mutex)
    #elif defined(WIN32_THREADS)
    #include <windows.h>
    #define MUTEX_PTR_DECLARE CRITICAL_SECTION*
    #define MUTEX_LOCK(mutex)  EnterCriticalSection(mutex)
    #define MUTEX_UNLOCK(mutex)  LeaveCriticalSection(mutex)
    #endif
    class Guard
    {
    public:
        Guard(MUTEX_PTR_DECLARE mutex): _mutex (mutex)
        {
            MUTEX_LOCK( _mutex );
        }
        ~Guard()
        {
            MUTEX_UNLOCK( _mutex );
        }
    private:
        MUTEX_PTR_DECLARE _mutex;
        // disable copy
        Guard(const Guard&);
        Guard& operator=(const Guard&);
    }

      因此经过上述封装包装后,在函数内使用同步机制时,不管函数的返回路径有多少条,都不需要在每条返回路径上去释放同步对象了,只要在需要使用同步机制的地方构造Guard对象即可,因为Guard对象在析构时自动回释放同步对象。这样就大大减少了出错的机会了。

  • 相关阅读:
    使用Application Insights 做分析
    UWP中GridView右击选中的实现
    Bing Map
    UWP深入学习六:Build better apps: Windows 10 by 10 development series
    从上往下打印二叉树
    二叉树中和为某一值的路径
    二叉树的镜像
    树的子结构
    由前序遍历和中序遍历构建二叉树
    二叉树常见题目
  • 原文地址:https://www.cnblogs.com/appsucc/p/2760396.html
Copyright © 2011-2022 走看看