00001 // -*- c++ -*- 00002 //------------------------------------------------------------------------------ 00003 // $Id: Semaphore.h,v 1.3 2005/08/19 03:18:24 vlg Exp $ 00004 //------------------------------------------------------------------------------ 00005 // Semaphore.h 00006 //------------------------------------------------------------------------------ 00007 // Copyright (c) 2000 by Vladislav Grinchenko 00008 // 00009 // This library is free software; you can redistribute it and/or 00010 // modify it under the terms of the GNU Library General Public 00011 // License as published by the Free Software Foundation; either 00012 // version 2 of the License, or (at your option) any later version. 00013 //------------------------------------------------------------------------------ 00014 00015 #ifndef SEMAPHORE_H 00016 #define SEMAPHORE_H 00017 00018 #include <sys/types.h> 00019 #include <sys/ipc.h> 00020 #include <sys/sem.h> 00021 00022 #include "assa/Assure.h" // trace() & Assert family 00023 00024 namespace ASSA { 00025 00064 class Semaphore 00065 { 00066 public: 00068 Semaphore (); 00069 00071 virtual ~Semaphore (); 00072 00080 int create (key_t key_, int initval_ = 1); 00081 00091 int open (key_t key_); 00092 00102 void close (); 00103 00112 void remove (); 00113 00117 void wait (); 00118 00122 void signal (); 00123 00128 void op (int val_); 00129 00131 key_t key () const { return m_key; } 00132 00134 int id () const { return m_id; } 00135 00139 void dump (void) const; 00140 00141 protected: 00144 void init (); 00145 00146 protected: 00148 key_t m_key; 00149 00151 int m_id; 00152 00153 protected: 00154 static const int BIGCOUNT; 00155 00158 static sembuf m_op_lock [2]; 00159 00163 static sembuf m_op_endcreate [2]; 00164 00168 static sembuf m_op_open [2]; 00169 00173 static sembuf m_op_close [3]; 00174 00177 static sembuf m_op_unlock [1]; 00178 00183 static sembuf m_op_op [1]; 00184 }; 00185 00186 inline 00187 Semaphore:: 00188 Semaphore () 00189 { 00190 trace_with_mask("Semaphore::Semaphore", SEM); 00191 00192 init (); 00193 } 00194 00195 inline 00196 Semaphore:: 00197 ~Semaphore () 00198 { 00199 trace_with_mask("Semaphore::~Semaphore", SEM); 00200 00201 if (m_id > 0) { 00202 this->close (); 00203 } 00204 } 00205 00206 inline void 00207 Semaphore:: 00208 init () 00209 { 00210 m_key = (key_t) -1; 00211 m_id = -1; 00212 } 00213 00214 inline void 00215 Semaphore:: 00216 wait () 00217 { 00218 trace_with_mask("Semaphore::wait", SEM); 00219 op (-1); 00220 } 00221 00222 inline void 00223 Semaphore:: 00224 signal () 00225 { 00226 trace_with_mask("Semaphore::signal", SEM); 00227 op (1); 00228 } 00229 00230 } // end namespace ASSA 00231 00232 00233 #endif /* SEMAPHORE_H */