Files
pip/pimutex.h

77 lines
2.0 KiB
C++

/*! \file pimutex.h
* \brief Mutex
*/
/*
PIP - Platform Independent Primitives
Mutex
Copyright (C) 2013 Ivan Pelipenko peri4ko@gmail.com
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef PIMUTEX_H
#define PIMUTEX_H
#include "piincludes.h"
#ifndef WINDOWS
# include <pthread.h>
#endif
class PIP_EXPORT PIMutex
{
public:
#ifndef WINDOWS
PIMutex() {
pthread_mutexattr_t attr;
pthread_mutexattr_init(&attr);
//pthread_mutexattr_settype(&attr, PTHREAD_PROCESS_SHARED);
pthread_mutex_init(&mutex, &attr);
pthread_mutexattr_destroy(&attr);
}
~PIMutex() {pthread_mutex_destroy(&mutex);}
void lock() {pthread_mutex_lock(&mutex);}
void unlock() {pthread_mutex_unlock(&mutex);}
bool tryLock() {return (pthread_mutex_trylock(&mutex) == 0);}
#else
PIMutex() {mutex = CreateMutex(0, false, 0);}
~PIMutex() {CloseHandle(mutex);}
void lock() {WaitForSingleObject(mutex, INFINITE);}
void unlock() {ReleaseMutex(mutex);}
bool tryLock() {return (WaitForSingleObject(mutex, 0) == WAIT_OBJECT_0);}
#endif
private:
#ifndef WINDOWS
pthread_mutex_t mutex;
#else
void * mutex;
#endif
};
class PIP_EXPORT PIMutexLocker
{
public:
PIMutexLocker(PIMutex * m): mutex(m) {mutex->lock();}
PIMutexLocker(PIMutex & m): mutex(&m) {mutex->lock();}
~PIMutexLocker() {mutex->unlock();}
private:
PIMutex * mutex;
};
#endif // PIMUTEX_H