]> git.tdb.fi Git - libs/core.git/blob - source/core/semaphore.h
164131acaaa8c19d5f94b9139be12fe9e05117a6
[libs/core.git] / source / core / semaphore.h
1 /*
2 This file is part of libmspframework
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         //Mutex &get_mutex() { return mutex; }
21         int   signal()     { MutexLock l(mutex); return pthread_cond_signal(&sem); }
22         int   broadcast()  { MutexLock l(mutex); return pthread_cond_broadcast(&sem); }
23         int   wait()       { mutex.lock(); return pthread_cond_wait(&sem, &mutex.mutex); }
24         int   wait(const Time::TimeDelta &);
25         ~Semaphore()       { pthread_cond_destroy(&sem); }
26 #else
27         Semaphore()        { sem=CreateSemaphore(0, 0, 32, 0); }
28         int   signal()     { return !ReleaseSemaphore(sem, 1, 0); }
29         int   broadcast()  { return !ReleaseSemaphore(sem, 32, 0); }
30         int   wait()       { return WaitForSingleObject(sem, INFINITE)==WAIT_OBJECT_0; }
31         int   wait(const Time::TimeDelta &);
32         ~Semaphore()       { CloseHandle(sem); }
33 #endif
34 private:
35         Mutex mutex;
36         SemaphoreHandle sem;
37 };
38
39 }
40
41 #endif