[C++]C++11, mutex 샘플 정리

intro

  • 이전엔 주로 아래와 같은식으로 사용했었는데, 역시나 C++11 편해졌네.
    class CCriticalSection
    {
    #if defined ( _WIN32 ) || defined ( _WIN64 )
    public:
      CCriticalSection(VOID)
      {
          InitializeCriticalSection(&mSync);
      }
      ~CCriticalSection(VOID)
      {
          DeleteCriticalSection(&mSync);
      }
      inline VOID Enter(VOID)
      {
          EnterCriticalSection(&mSync);
      }
      inline VOID Leave(VOID)
      {
          LeaveCriticalSection(&mSync);
      }
    private:
      CRITICAL_SECTION    mSync;
    #else
    public:
      CCriticalSection(void)
      {
          pthread_mutexattr_t     attr;
          if ( pthread_mutexattr_init( &attr ) != 0 )
          {
          }            
          if ( pthread_mutexattr_settype( &attr, PTHREAD_MUTEX_RECURSIVE ) != 0 )
          {
          }
          if ( pthread_mutex_init( &mSync, &attr ) != 0 )
          {
          }
          if ( pthread_mutexattr_destroy( &attr ) != 0 )
          {
          }
      }
      ~CCriticalSection(void)
      {
          pthread_mutex_destroy( &mSync );
      }
      inline void Enter(void)
      {
          pthread_mutex_lock( &mSync );
      }
      inline void Leave(void)
      {
          pthread_mutex_unlock( &mSync );
      }
    private:
      pthread_mutex_t mSync;
    #endif
    };
    

sample

  • 아래는 자주 사용할만한 기능에 대한 샘플들
    #include <mutex>
    void test_mutex()
    {
      std::mutex mtx_lock;
      //case1
      {
          mtx_lock.lock();
          //do something
          mtx_lock.unlock();
      }
      //case2
      {
          //mutex 소유권을 획득하면 true를 리턴, 소유할수없으면 false를..
          bool ret = mtx_lock.try_lock();
          if (ret == true)
          {
              //....
              mtx_lock.unlock();
          }
          else
          {
              //....
          }
      }
      //case3, unique_lock 도 비슷
      {
          {
              //scoped lock
              std::lock_guard<std::mutex> guard(mtx_lock);
              //do something 
          }
      }
      //case4
      {
          //InitializeCriticalSectionAndSpinCount 랑 조금은 비슷한듯, 3초동안 lock시도 해보고 안되면 말기
          std::timed_mutex timed_mutex;
          bool ret = timed_mutex.try_lock_for(std::chrono::seconds(3));
          if (true == ret)
          {
              //do something
              timed_mutex.unlock();
          }
          else
          {
              //do something
          }
      }
    }