If you really insist on using POSIX semaphores and not Boost, you can of course wrap sem_t
in a class:
class Semaphore {
sem_t sem;
public:
Semaphore(int shared, unsigned value)
{ sem_init(&sem, shared, value); }
~Semaphore() { sem_destroy(&sem); }
int wait() { return sem_wait(&sem); }
int try_wait() { return sem_trywait(&sem); }
int unlock() { return sem_post(&sem); }
};
Exercise for the reader: You may want to add exceptions instead of C-style error codes and perhaps other features. Also, this class should be noncopyable. The easiest way to achieve that is inheriting from boost::noncopyable
;)
Edit: as @Ringding remarks, looping on EINTR
would be a very wise thing to do.
int Semaphore::wait()
{
int r;
do {
r = sem_wait(&sem);
} while (r == -1 && errno == EINTR);
return r;
}