1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| class semaphore
{
public:
typedef semaphore self;
typedef scoped_lock<self> scoped_lock;
private:
sem_t *sem;
semaphore(const self &);
const self &operator=(const self &);
public:
inline semaphore( ) { sem = sem_open( "", O_CREAT, S_IRUSR | S_IWUSR, 1 ); }//assert_thread(sem_init(&sem,0,0)); };
inline semaphore(int n) { sem = sem_open( "", O_CREAT, S_IRUSR | S_IWUSR, n ); }//assert_thread(sem_init(&sem,0,n)); };
inline ~semaphore() { sem_close(sem); } //assert_thread(sem_destroy(&sem)); }
inline void release() { assert_thread(sem_post(sem)); }
#if !defined(__ICL) && !defined(_MSC_VER)
inline void release(int n) { for (int i=0; i<n; ++i) release(); }
#else
inline void release(int n) { assert_thread(sem_post_multiple(sem,n)); }
#endif
inline void acquire() { assert_thread(sem_wait(sem)); }
inline void acquire(int n) { for (int i=0; i<n; ++i) acquire(); }
inline bool try_acquire() { return sem_trywait(sem)!=-1; }
inline int try_acquire(int n) { for (int i=0; i<n; ++i) if (!try_acquire()) return i; return n; }
inline unsigned int value() { int sval; assert_thread(sem_getvalue(sem, &sval)); return sval; }
}; |