namespace Msp {
-#ifndef WIN32
int Semaphore::wait(const Time::TimeDelta &d)
{
+#ifndef WIN32
Time::TimeStamp ts=Time::now()+d;
timespec timeout;
timeout.tv_nsec=(ts.raw()%1000000)*1000;
MutexLock l(mutex);
- int r=pthread_cond_timedwait(&cond, &mutex.mutex, &timeout);
+ int r=pthread_cond_timedwait(&sem, &mutex.mutex, &timeout);
if(r==ETIMEDOUT)
return 1;
else if(r)
return -1;
return 0;
-}
+#else
+ return WaitForSingleObject(sem, (DWORD)(d/Time::usec))==WAIT_OBJECT_0;
#endif
+}
} // namespace Msp
#ifndef MSP_FRAMEWORK_SEMAPHORE_H_
#define MSP_FRAMEWORK_SEMAPHORE_H_
-#include <pthread.h>
#include "mutex.h"
+#include "types.h"
#include "../time/timedelta.h"
namespace Msp {
{
public:
#ifndef WIN32
- Semaphore() { pthread_cond_init(&cond, 0); }
+ Semaphore() { pthread_cond_init(&sem, 0); }
//Mutex &get_mutex() { return mutex; }
- int signal() { MutexLock l(mutex); return pthread_cond_signal(&cond); }
- int broadcast() { MutexLock l(mutex); return pthread_cond_broadcast(&cond); }
- int wait() { mutex.lock(); return pthread_cond_wait(&cond, &mutex.mutex); }
+ int signal() { MutexLock l(mutex); return pthread_cond_signal(&sem); }
+ int broadcast() { MutexLock l(mutex); return pthread_cond_broadcast(&sem); }
+ int wait() { mutex.lock(); return pthread_cond_wait(&sem, &mutex.mutex); }
int wait(const Time::TimeDelta &);
- ~Semaphore() { pthread_cond_destroy(&cond); }
+ ~Semaphore() { pthread_cond_destroy(&sem); }
+#else
+ Semaphore() { sem=CreateSemaphore(0, 0, 32, 0); }
+ int signal() { return !ReleaseSemaphore(sem, 1, 0); }
+ int broadcast() { return !ReleaseSemaphore(sem, 32, 0); }
+ int wait() { return WaitForSingleObject(sem, INFINITE)==WAIT_OBJECT_0; }
+ int wait(const Time::TimeDelta &);
+ ~Semaphore() { CloseHandle(sem); }
#endif
private:
Mutex mutex;
- pthread_cond_t cond;
+ SemaphoreHandle sem;
};
}
#ifdef WIN32
typedef HANDLE ThreadHandle;
typedef HANDLE MutexHandle;
+typedef HANDLE SemaphoreHandle;
#else
typedef pthread_t ThreadHandle;
typedef pthread_mutex_t MutexHandle;
+typedef pthread_cond_t SemaphoreHandle;
#endif
} // namespace Msp
*/
int64_t raw() const { return usec; }
+#ifndef WIN32
/**
Fills in a timespec struct. To get a meaningful scalar value from the
TimeDelta, divide with one of the values in units.h.
*/
void fill_timespec(timespec &ts) const { ts.tv_sec=usec/1000000; ts.tv_nsec=(usec%1000000)*1000; }
+#endif
TimeDelta operator+(const TimeDelta &t) const { return TimeDelta(usec+t.usec); }
TimeDelta &operator+=(const TimeDelta &t) { usec+=t.usec; return *this; }