RAUL  0.5.1
Semaphore.hpp
1 /* This file is part of Raul.
2  * Copyright (C) 2007 Dave Robillard <http://drobilla.net>
3  *
4  * Raul is free software; you can redistribute it and/or modify it under the
5  * terms of the GNU General Public License as published by the Free Software
6  * Foundation; either version 2 of the License, or (at your option) any later
7  * version.
8  *
9  * Raul is distributed in the hope that it will be useful, but WITHOUT ANY
10  * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
11  * FOR A PARTICULAR PURPOSE. See the GNU General Public License for details.
12  *
13  * You should have received a copy of the GNU General Public License along
14  * with this program; if not, write to the Free Software Foundation, Inc.,
15  * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
16  */
17 
18 #ifndef RAUL_SEMAPHORE_HPP
19 #define RAUL_SEMAPHORE_HPP
20 
21 #include <semaphore.h>
22 #include <boost/utility.hpp>
23 
24 namespace Raul {
25 
26 
39 class Semaphore : boost::noncopyable {
40 public:
41  inline Semaphore(unsigned int initial) { sem_init(&_sem, 0, initial); }
42 
43  inline ~Semaphore() { sem_destroy(&_sem); }
44 
45  inline void reset(unsigned int initial) {
46  sem_destroy(&_sem);
47  sem_init(&_sem, 0, initial);
48  }
49 
50  inline bool has_waiter() {
51  int val;
52  sem_getvalue(&_sem, &val);
53  return (val <= 0);
54  }
55 
60  inline void post() { sem_post(&_sem); }
61 
69  inline void wait() { while (sem_wait(&_sem) != 0) ; }
70 
77  inline bool try_wait() { return (sem_trywait(&_sem) == 0); }
78 
79 private:
80  sem_t _sem;
81 };
82 
83 
84 } // namespace Raul
85 
86 #endif // RAUL_SEMAPHORE_HPP
Trivial wrapper around POSIX semaphores (zero memory overhead).
Definition: Semaphore.hpp:39
bool try_wait()
Non-blocking version of wait().
Definition: Semaphore.hpp:77
void wait()
Wait until count is &gt; 0, then decrement.
Definition: Semaphore.hpp:69
void post()
Increment (and signal any waiters).
Definition: Semaphore.hpp:60