Add mechanism to reset/lock semaphores
[ardour.git] / libs / pbd / pbd / semutils.h
1 /*
2     Copyright (C) 2010 Paul Davis
3
4     This program is free software; you can redistribute it and/or modify
5     it under the terms of the GNU General Public License as published by
6     the Free Software Foundation; either version 2 of the License, or
7     (at your option) any later version.
8
9     This program is distributed in the hope that it will be useful,
10     but WITHOUT ANY WARRANTY; without even the implied warranty of
11     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12     GNU General Public License for more details.
13
14     You should have received a copy of the GNU General Public License
15     along with this program; if not, write to the Free Software
16     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17 */
18
19 #ifndef __pbd_semutils_h__
20 #define __pbd_semutils_h__
21
22 #if (defined PLATFORM_WINDOWS && !defined USE_PTW32_SEMAPHORE)
23 #define WINDOWS_SEMAPHORE 1
24 #endif
25
26 #ifdef WINDOWS_SEMAPHORE
27 #include <windows.h>
28 #else
29 #include <pthread.h>
30 #include <semaphore.h>
31 #endif
32
33 #include "pbd/libpbd_visibility.h"
34
35 namespace PBD {
36
37 class LIBPBD_API Semaphore {
38   private:
39 #ifdef WINDOWS_SEMAPHORE
40         HANDLE _sem;
41
42 #elif __APPLE__
43         sem_t* _sem;
44         sem_t* ptr_to_sem() const { return _sem; }
45 #else
46         mutable sem_t _sem;
47         sem_t* ptr_to_sem() const { return &_sem; }
48 #endif
49
50   public:
51         Semaphore (const char* name, int val);
52         ~Semaphore ();
53
54 #ifdef WINDOWS_SEMAPHORE
55
56         int signal ();
57         int wait ();
58         int reset ();
59
60 #else
61         int signal () { return sem_post (ptr_to_sem()); }
62         int wait () { return sem_wait (ptr_to_sem()); }
63         int reset () { int rv = 0 ; while (sem_trywait (ptr_to_sem()) == 0) ++rv; return rv; }
64 #endif
65 };
66
67 }
68
69 #endif /* __pbd_semutils_h__ */