laforge
/
openbts-osmo
Archived
1
0
Fork 0

Implementation of Semaphore.

This commit is contained in:
Alexander Chemeris 2010-08-18 22:52:33 +04:00 committed by Thomas Tsou
parent 2ab4ca6648
commit 971b6ba700
2 changed files with 40 additions and 0 deletions

View File

@ -96,6 +96,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)
{

View File

@ -29,6 +29,7 @@
#include <pthread.h>
#include <iostream>
#include <assert.h>
#include <semaphore.h>
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);