]> git.tdb.fi Git - libs/core.git/blob - source/core/semaphore.h
1cf3cd6ad11b44402eacca11d415d9df60941916
[libs/core.git] / source / core / semaphore.h
1 /*
2 This file is part of libmspcore
3 Copyright © 2006  Mikko Rasa, Mikkosoft Productions
4 Distributed under the LGPL
5 */
6 #ifndef MSP_FRAMEWORK_SEMAPHORE_H_
7 #define MSP_FRAMEWORK_SEMAPHORE_H_
8
9 #include "mutex.h"
10 #include "types.h"
11 #include "../time/timedelta.h"
12
13 namespace Msp {
14
15 class Semaphore
16 {
17 public:
18 #ifndef WIN32
19         Semaphore()        { pthread_cond_init(&sem, 0); }
20         int   signal()     { MutexLock l(mutex); return pthread_cond_signal(&sem); }
21         int   broadcast()  { MutexLock l(mutex); return pthread_cond_broadcast(&sem); }
22         int   wait()       { MutexLock l(mutex); return pthread_cond_wait(&sem, &mutex.mutex); }
23         int   wait(const Time::TimeDelta &);
24         ~Semaphore()       { pthread_cond_destroy(&sem); }
25 #else
26         Semaphore()        { sem=CreateSemaphore(0, 0, 32, 0); }
27         int   signal()     { return !ReleaseSemaphore(sem, 1, 0); }
28         int   broadcast()  { return !ReleaseSemaphore(sem, 32, 0); }
29         int   wait()       { return WaitForSingleObject(sem, INFINITE)==WAIT_OBJECT_0; }
30         int   wait(const Time::TimeDelta &);
31         ~Semaphore()       { CloseHandle(sem); }
32 #endif
33 private:
34 #ifndef WIN32
35         Mutex mutex;
36 #endif
37         SemaphoreHandle sem;
38 };
39
40 }
41
42 #endif