Welcome
Example Code
C and C++
Argument Parsing
Create Subprocess
Create Thread
Is Subprocess Done
Non-Blocking File (Unix)
Mutex (Lock)
TCP Server
Wait For File (Unix)
Python
Non-Blocking Read

Monju System Architects



Code - C++ - Mutex (Lock)
Download: mutex.cpp (the linked-to file is properly tabbed)
Requires: mutex.h
//  Copyright (c) 2007, Monju System Architects
//
//  Released under the Monju-Public copyright license:
//
//  Permission is hereby granted, free of charge, to any person or entity
//  obtaining a copy of this software and associated documentation files
//  (the "Software"), to deal in the Software without restriction,
//  including without limitation the rights to use, copy, modify, merge,
//  publish, distribute, sublicense, and/or sell copies and modifications
//  of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
//
//  The above copyright notice and this permission notice shall be
//  included in all copies or substantial portions of published, sold, or
//  ownership-transferred versions of the Software. This notice is not
//  required for binary-only releases or binary-only derivatives of the
//  Software, or documentation provided with binary-only releases and
//  binary-only derivatives.
//
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
//  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
//  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
//  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
//  CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
//  TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
//  SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.




//  INCLUDES.
#include "public/mutex.h"




//  closeMutex()
void closeMutex(MUTEX_TYPE& mutex) {
    #ifdef _WIN32
        CloseHandle(mutex);
    #else
        pthread_mutex_destroy(&mutex);
    #endif
}



//  createMutex()
MUTEX_TYPE createMutex() {
    #ifdef _WIN32
        MUTEX_TYPE mutex = CreateMutex(NULL, FALSE, NULL);
        if (mutex == NULL) {
            throw("CreateMutex() failed.");
        }
    #else
        MUTEX_TYPE mutex;
        if (0 != pthread_mutex_init(&mutex, NULL)) {
            throw("pthread_mutex_init() failed.");
        }
    #endif
    return mutex;
}



//  lockMutex()
void lockMutex(MUTEX_TYPE& mutex) {
    #ifdef _WIN32
        WaitForSingleObject(mutex, INFINITE);
    #else
        pthread_mutex_lock(&mutex);
    #endif
}



//  unlockMutex()
void unlockMutex(MUTEX_TYPE& mutex) {
    #ifdef _WIN32
        ReleaseMutex(mutex);
    #else
          pthread_mutex_unlock(&mutex);
    #endif
}