multithreading - Object-oriented semaphore usage in C++ -


i know how use unix semaphores in c. before using them must call constructor-ish function named sem_init , after using them have call destructor-like function named sem_destroy.

i know can keep doing in c++ because of backwards compatibility c, c++ have real object-oriented way use semaphores?

if insist on using posix semaphores , not boost, can of course wrap sem_t in 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 reader: may want add exceptions instead of c-style error codes , perhaps other features. also, class should noncopyable. easiest way achieve inheriting boost::noncopyable ;)

edit: @ringding remarks, looping on eintr wise thing do.

int semaphore::wait() {     int r;     {         r = sem_wait(&sem);     } while (r == -1 && errno == eintr);     return r; } 

Comments

Popular posts from this blog

java - SNMP4J General Variable Binding Error -

windows - Python Service Installation - "Could not find PythonClass entry" -

Determine if a XmlNode is empty or null in C#? -