VIZ++ Class: Mutex

 VIZ++ Class Library  VIZ++ Samples  VIZ++ ClassTree 

Source code

/*
 * Mutex.h 
 * Copyright (c) 2015 Antillia.com TOSHIYUKI ARAI. ALL RIGHTS RESERVED. 
 */


#pragma once

#include <viz++\Object.h>
#include <viz++\InvalidHandleException.h>
#include <viz++\String.h>


namespace VIZ {

class Mutex :public Object {
private:
  HANDLE hMutex;
  String name;

public:
  /**
   */
  Mutex(const TCHAR* id=_T("SolMutex"))
    :hMutex(NULL),
    name(_T(""))
  {
    if (id) {
      this->name = id;
      this->name.replace('\\', '/');
    }
  }


public:
  /**
   */
  Mutex(LPSECURITY_ATTRIBUTES security, BOOL owner, const TCHAR* id)
    :hMutex(NULL),name(_T(""))
  {
    if (id) {
      this->name = id;
      this->name.replace('\\', '/');
    }
    
    this->hMutex = ::CreateMutex(security, owner, (const TCHAR*)this->name);
    if(hMutex == NULL) {
      throw InvalidHandleException("Failed to create a mutex",
        ::GetLastError());
    }
  }
  

public:
  /**
   */
  ~Mutex() {
    close();
  }

public:
  /**
   */
  //Apply for mutext created Mutext(id)
  DWORD  lock() {
    DWORD rc = -1;
    if (this->hMutex) {
      close();
    }

    this->hMutex = CreateMutex(NULL, FALSE, (const TCHAR*)name);
    
    if (this->hMutex) {
      // Enter an infinite loop, should be modified to handle 
      //Windows message;
      rc = WaitForSingleObject(this->hMutex, INFINITE);
    }
    
    return rc;  
  }

public:
  /**
   */
  void  unlock() {
    close();
  }



public:
  void close() {
    if(this->hMutex) {
      ::ReleaseMutex(this->hMutex);
      ::CloseHandle(this->hMutex);
      this->hMutex = NULL;
    }
  }

  DWORD  wait(DWORD millisec = INFINITE) {
      return ::WaitForSingleObject(hMutex, millisec);
  }

  BOOL  release() {
      return ::ReleaseMutex(hMutex);
  }
};

}


Last modified: 10 Feb 2017

Copyright (c) 2009-2017 Antillia.com ALL RIGHTS RESERVED.