From e13940488427cf7e9456bf9123dac5030838e218 Mon Sep 17 00:00:00 2001 From: Alexander Chemeris Date: Wed, 18 Aug 2010 22:52:33 +0400 Subject: [PATCH] Implementation of Semaphore. --- public-trunk/CommonLibs/Threads.cpp | 9 +++++++++ public-trunk/CommonLibs/Threads.h | 31 +++++++++++++++++++++++++++++ 2 files changed, 40 insertions(+) diff --git a/public-trunk/CommonLibs/Threads.cpp b/public-trunk/CommonLibs/Threads.cpp index df2e3a1..2628ab1 100644 --- a/public-trunk/CommonLibs/Threads.cpp +++ b/public-trunk/CommonLibs/Threads.cpp @@ -95,6 +95,15 @@ void Signal::wait(Mutex& wMutex, unsigned timeout) const pthread_cond_timedwait(&mSignal,&wMutex.mMutex,&waitTime); } +/** Wait for semaphore to be signaled with timeout. +* @returns 0 on success, -1 on error or timeout. +*/ +int ThreadSemaphore::wait(unsigned timeout) const +{ + Timeval then(timeout); + struct timespec waitTime = then.timespec(); + return sem_timedwait(&mSem,&waitTime); +} void Thread::start(void *(*task)(void*), void *arg) { diff --git a/public-trunk/CommonLibs/Threads.h b/public-trunk/CommonLibs/Threads.h index 0f12972..4b65215 100644 --- a/public-trunk/CommonLibs/Threads.h +++ b/public-trunk/CommonLibs/Threads.h @@ -29,6 +29,7 @@ #include #include #include +#include class Mutex; @@ -120,7 +121,37 @@ class Signal { }; +/** Semaphore */ +class ThreadSemaphore { + private: + + mutable sem_t mSem; + + public: + + ThreadSemaphore(int pshared = 0, unsigned value = 0) { assert(sem_init(&mSem,pshared,value)!=-1); } + + ~ThreadSemaphore() { sem_destroy(&mSem); } + + /** Wait for semaphore to be signaled with timeout. + * @returns 0 on success, -1 on error or timeout. + */ + int wait (unsigned timeout) const; + + /** Wait for semaphore to be signaled infinitely. + * @returns 0 on success, -1 on error. + */ + int wait() const { return sem_wait(&mSem); } + + /** Check if semaphore has been signaled and disarm it. + * @returns 0 if semaphore has been signaled, -1 in other cases. + */ + int trywait() const { return sem_trywait(&mSem); } + + int post() { return sem_post (&mSem); } + +}; #define START_THREAD(thread,function,argument) \ thread.start((void *(*)(void*))function, (void*)argument);