SOL9 2.0 Class: Mutex

 SOL9 C++ Class Library  SOL9 Samples  SOL9 Tutorial  SOL9 FAQ  SOL9 ClassTree 

Source code

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


// SOL++2000
#pragma once

#include <sol\Object.h>
#include <sol\InvalidHandleException.h>
#include <sol\String.h>


namespace SOL {

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

public:
    /**
     */
    Mutex(const TCHAR* id)
        :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: 1 Feb 2012

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