2

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

I know I can keep doing this in C++ because of its backwards compatibility with C, but does C++ have a real object-oriented way to use semaphores?

Pieter
  • 31,619
  • 76
  • 167
  • 242
  • See http://stackoverflow.com/questions/3928853/how-can-i-achieve-something-similar-to-a-semaphore-using-boost-in-c – CharlesB Jan 26 '11 at 11:26
  • I've heard of Boost before, but haven't used it. Are you saying that I need to download additional libraries if I want to use semaphores in an OO way? Then I'll just stick with the already included `semaphore.h` library. – Pieter Jan 26 '11 at 11:32

3 Answers3

3

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;
}
Fred Foo
  • 355,277
  • 75
  • 744
  • 836
2

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

Boost.Interprocess is the library you need for your question. It provides an abstraction over the inter-process communnication mechanisms.

This is an example of how to use semaphores.

zundr
  • 156
  • 3
0

C++0x has no semaphores? How to synchronize threads?

Community
  • 1
  • 1
Maxim Egorushkin
  • 131,725
  • 17
  • 180
  • 271