Using Object Oriented Semaphore in C ++

I know how to use Unix semaphores in C. Before using them, I have to call a constructor-ish function called sem_init , and after using them I need to call a destructor function called sem_destroy .

I know that I can continue to do this in C ++ because of its backward compatibility with C, but does C ++ have a real object-oriented way of using semaphores?

+2
source share
3 answers

If you really insist on using POSIX semaphores rather than 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 might want to add exceptions instead of C-style error codes and possibly other functions. In addition, this class must not be copyable. The easiest way to achieve this is to inherit from boost::noncopyable ;)

Edit : as @Ringding's remark, making a loop on an EINTR would be very reasonable.

 int Semaphore::wait() { int r; do { r = sem_wait(&sem); } while (r == -1 && errno == EINTR); return r; } 
+2
source

You should use Boost libraries (if you don't know them, they are for C ++, which is the JDK for Java).

Boost.Interprocess is the library you need for your question. It provides an abstraction of interprocess communication mechanisms.

This is an example of using semaphores.

+2
source

Source: https://habr.com/ru/post/1341423/


All Articles