3 This file is part of libmspcore
4 Copyright © 2006 Mikko Rasa, Mikkosoft Productions
5 Distributed under the LGPL
12 #include "semaphore.h"
13 #include "../time/timestamp.h"
14 #include "../time/units.h"
15 #include "../time/utils.h"
19 Semaphore::Semaphore():
26 Semaphore::Semaphore(Mutex &m):
33 void Semaphore::init()
37 sem=CreateSemaphore(0, 0, 32, 0);
39 pthread_cond_init(&sem, 0);
43 Semaphore::~Semaphore()
50 pthread_cond_destroy(&sem);
55 int Semaphore::signal()
60 int ret=!ReleaseSemaphore(sem, 1, 0);
62 unsigned old_count=count;
64 while(count==old_count)
71 int Semaphore::broadcast()
75 int ret=!ReleaseSemaphore(sem, count, 0);
89 DWORD ret=WaitForSingleObject(sem, INFINITE);
93 return ret==WAIT_OBJECT_0;
97 int Semaphore::wait(const Time::TimeDelta &d)
100 Time::TimeStamp ts=Time::now()+d;
103 timeout.tv_sec=ts.raw()/1000000;
104 timeout.tv_nsec=(ts.raw()%1000000)*1000;
106 int r=pthread_cond_timedwait(&sem, &mutex->mutex, &timeout);
115 DWORD ret=WaitForSingleObject(sem, (DWORD)(d/Time::usec));
118 return ret==WAIT_OBJECT_0;