Semaphores.h

Go to the documentation of this file.
00001 /* 
00002  * Copyright (C) 2006-2010 Jacek Sieka, arnetheduck on gmail point com
00003  *
00004  * This program is free software; you can redistribute it and/or modify
00005  * it under the terms of the GNU General Public License as published by
00006  * the Free Software Foundation; either version 2 of the License, or
00007  * (at your option) any later version.
00008  *
00009  * This program is distributed in the hope that it will be useful,
00010  * but WITHOUT ANY WARRANTY; without even the implied warranty of
00011  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00012  * GNU General Public License for more details.
00013  *
00014  * You should have received a copy of the GNU General Public License
00015  * along with this program; if not, write to the Free Software
00016  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
00017  */
00018 
00019 #ifndef ADCHPP_SEMAPHORES_H
00020 #define ADCHPP_SEMAPHORES_H
00021 
00022 namespace adchpp {
00023     
00024 #ifndef _WIN32
00025 #include <semaphore.h>
00026 #endif
00027 
00028 class Semaphore  
00029 {
00030 #ifdef _WIN32
00031 public:
00032     Semaphore() throw() {
00033         h = CreateSemaphore(NULL, 0, MAXLONG, NULL);
00034     };
00035 
00036     void signal() throw() {
00037         ReleaseSemaphore(h, 1, NULL);
00038     }
00039 
00040     enum Results {
00041         RESULT_OK,
00042         RESULT_TIMEOUT,
00043         RESULT_MESSAGE
00044     };
00045     Results waitMsg(uint32_t millis = INFINITE) throw() { 
00046         switch(MsgWaitForMultipleObjects(1, &h, FALSE, millis, QS_ALLEVENTS)) {
00047         case WAIT_TIMEOUT: return RESULT_TIMEOUT;
00048         case WAIT_OBJECT_0: return RESULT_OK;
00049         case WAIT_OBJECT_0 + 1: return RESULT_MESSAGE;
00050         default: dcasserta(false);
00051         }
00052 #ifndef NDEBUG
00053         return RESULT_TIMEOUT;
00054 #endif
00055     };
00056     bool wait(uint32_t millis = INFINITE) throw() { return WaitForSingleObject(h, millis) == WAIT_OBJECT_0; };
00057     
00058     ~Semaphore() throw() {
00059         CloseHandle(h);
00060     };
00061 
00062 private:
00063     HANDLE h;
00064 #else
00065 public:
00066     Semaphore() throw() { sem_init(&sem, 0, 0); };
00067     ~Semaphore() throw() { sem_destroy(&sem); };
00068     void signal() throw() { sem_post(&sem); };
00069     bool wait() throw() { sem_wait(&sem); return true; };
00070     bool wait(uint32_t millis) throw() {
00072         uint32_t w = 0;
00073         while(w < millis) {
00074             if(sem_trywait(&sem) == 0)
00075                 return true;
00076             w += 100;
00077             Thread::sleep(100);
00078         }
00079         return false;
00080     }
00081 private:
00082     sem_t sem;
00083 #endif
00084 };
00085 
00086 }
00087 
00088 #endif // SEMAPHORES_H
Generated on Sat Nov 27 23:37:53 2010 for adchpp by  doxygen 1.6.3