📄 oxsemi_sem.h
字号:
#ifndef INC_SYSLIB_OXSEMISEM_H#define INC_SYSLIB_OXSEMISEM_H#include "semaphore.h"#include "pthread.h"namespace oxsemi{namespace syslib{ /** * base class to represent a platform-independent semaphore */ class oxsemi_sem { public: enum { OK = 0, ERROR = -1 }; /** * give the semaphore; ie allow another thread to take it */ virtual void give() = 0; /** * take the semaphore, blocking until it's available or until we time out * @param timeout an int representing the number of ticks to wait until * we give up * @return OK if the semaphore was successfully taken */ virtual int take(int timeout = 0) = 0; /** * synonymous with take(), used to wrap semaphores up in scoped_lock<> */ void lock() { take(); } /** * synonymous with give(), used to wrap semaphores up in scoped_lock<> */ void unlock() { give(); } virtual ~oxsemi_sem() { } }; /** * class to encapsulate a binary semaphore */ class oxsemi_bsem : public oxsemi_sem { public: enum state { semEmpty = 0, semFull }; /** * constructor * @param initState an int (effectively a boolean) defining the initial * state of the sempahore */ oxsemi_bsem(int initState = semFull) { sem_init(&semaphore_, 0, initState); } int take(int timeout = 0) { ASSERT(0 == timeout); sem_wait(&semaphore_); return OK; } void give() { sem_post(&semaphore_); } ~oxsemi_bsem() { sem_destroy(&semaphore_); } private: sem_t semaphore_; }; /** * class to encapsulate a counting semaphore */ class oxsemi_csem : public oxsemi_sem { public: /** * constructor * @param initCount an int which specifies the initial availability * of the semaphore, ie how many times it can be take()n without * blocking before the first give() */ oxsemi_csem(int initCount = 0) { sem_init(&semaphore_, 0, initCount); } int take(int timeout = 0) { ASSERT(0 == timeout); sem_wait(&semaphore_); return OK; } void give() { sem_post(&semaphore_); } ~oxsemi_csem() { // should this be sem_destroy() ? sem_post(&semaphore_); } private: sem_t semaphore_; }; /** * class to encapsulate a mutex */ class oxsemi_msem : public oxsemi_sem { public: static const int semPriorityInheritance = 0x1; /** * constructor * @param initFlags an int (effectively a boolean on the lowest bit) * which specifies whether priority inheritance applies */ oxsemi_msem(int initFlags = semPriorityInheritance) { ASSERT(semPriorityInheritance == initFlags); pthread_mutexattr_t mutexAttr; pthread_mutexattr_init(&mutexAttr); pthread_mutexattr_settype(&mutexAttr, PTHREAD_MUTEX_RECURSIVE); pthread_mutex_init(&mutex_, &mutexAttr); pthread_mutexattr_destroy(&mutexAttr); } ~oxsemi_msem() { pthread_mutex_destroy(&mutex_); } int take(int timeout = 0) { ASSERT(timeout == 0); pthread_mutex_lock(&mutex_); return OK; } void give() { pthread_mutex_unlock(&mutex_); } private: pthread_mutex_t mutex_; };};};#endif
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -