VideoTools
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Pages
gsemaphore_posix.cpp
Go to the documentation of this file.
1 //
2 // Copyright (C) 2017 Graeme Walker
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 3 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, see <http://www.gnu.org/licenses/>.
16 // ===
17 //
18 // gsemaphore_posix.cpp
19 //
20 
21 #include "gdef.h"
22 #include "gsemaphore.h"
23 #include "gprocess.h"
24 #include "gassert.h"
25 #include <semaphore.h>
26 #include <errno.h>
27 
28 typedef char static_assert_sem_t_fits_in_storage_type[sizeof(sem_t)<=sizeof(G::Semaphore::storage_type)?1:-1] ; // if this fails to compile then increase the size of the Semaphore::storage_type::filler array
29 
30 static sem_t * ptr( G::Semaphore * s )
31 {
32  return reinterpret_cast<sem_t*>(s) ;
33 }
34 
35 // ==
36 
38 {
39  // SignalSafe
40  return reinterpret_cast<G::Semaphore*>(p) ;
41 }
42 
43 G::Semaphore::Semaphore( unsigned int initial_value )
44 {
45  G_ASSERT( reinterpret_cast<void*>(this) == reinterpret_cast<void*>(&m_storage) ) ;
46  int shared = 1 ;
47  if( 0 != ::sem_init( ptr(this) , shared , initial_value ) )
48  {
49  int e = errno ;
50  throw Error( "sem_init" , G::Process::strerror(e) ) ;
51  }
52 }
53 
55 {
56  ::sem_destroy( ptr(this) ) ;
57 }
58 
60 {
61  // SignalSafe
62  ::sem_post( ptr(this) ) ;
63 }
64 
65 #ifdef G_UNIX_LINUX
66 bool G::Semaphore::decrement( int timeout )
67 {
68  struct timespec ts = { ::time(nullptr)+timeout , 0 } ;
69  int rc = ::sem_timedwait( ptr(this) , &ts ) ;
70  return rc == 0 ;
71 }
72 #endif
73 
75 {
76  ::sem_wait( ptr(this) ) ;
77 }
78 
79 /// \file gsemaphore_posix.cpp
void decrement()
Decrement-but-block-if-zero operator.
static Semaphore * at(storage_type *)
Syntactic sugar to return an object pointer corresponding to the given storage pointer.
void increment()
Increment operator. Used for mutex unlocking.
A semaphore class with a posix or sysv implementation chosen at build-time.
Definition: gsemaphore.h:47
~Semaphore()
Destroys the semaphore.
semaphore storage
Definition: gsemaphore.h:51
Semaphore(unsigned int initial_value=1U)
Constructor for a new anonymous semaphore, typically located inside a shared memory segment using "pl...