3 #include <msp/core/systemerror.h>
4 #include <msp/time/rawtime_private.h>
5 #include <msp/time/timestamp.h>
6 #include <msp/time/utils.h>
8 #include "mutex_private.h"
13 struct Semaphore::Private
22 Semaphore::Semaphore(unsigned limit):
25 pthread_cond_init(&priv->cond, nullptr);
29 Semaphore::~Semaphore()
31 pthread_cond_destroy(&priv->cond);
35 void Semaphore::signal()
37 MutexLock mlock(priv->mutex);
38 if(priv->count<priv->limit)
40 if(int err = pthread_cond_signal(&priv->cond))
41 throw system_error("pthread_cond_signal", err);
44 void Semaphore::wait()
46 MutexLock mlock(priv->mutex);
48 if(int err = pthread_cond_wait(&priv->cond, &priv->mutex.priv->mutex))
49 throw system_error("pthread_cond_wait", err);
53 bool Semaphore::wait(const Time::TimeDelta &d)
55 timespec timeout = Time::rawtime_to_timespec((Time::now()+d).raw());
57 int err = pthread_cond_timedwait(&priv->cond, &priv->mutex.priv->mutex, &timeout);
58 if(err && err!=ETIMEDOUT)
59 throw system_error("pthread_cond_timedwait", err);