1

C++20 will bring counting and binary semaphores into the language. In the mean time, is there a library for C++11/14/17 providing similar functionality?

Required features:

  • Supported on Linux
  • Supports at least binary semaphores
  • Gratis
  • Libre license

Desired features:

  • Supports counting semaphores
  • Supported on any platform which offers POSIX threads/semaphores
  • Small (i.e. not going to pull in Boost or Abseil etc.)
  • Non-minuscule userbase
  • Actively-maintained
  • Makes decent use of C++11/14/17 features, and particularly - plays nicely with std::thread if necessary.
  • Documented

2 Answers 2

0

A little weak on the requirements, but interesting nonetheless:

Erik Rigtorp's BinarySemaphore library, which is based on futexes. These are a combination kernel-space cum user-space synchronization mechanism which can be quite speedy, since most interaction with it is with an atomic value in userspace and does not require system calls.

The catch is that futexes are not a POSIX mechanism, and thus don't exist on all operating systems. It seems this is a Linux-only library. Also, the author has not implemented counting semaphores.

0

Benoit Dacacche has written a small library of C++ wrappers for BSD sockets, POSIX threads and POSIX semaphores: CPPWrappers.

Its semaphore wrapper is extremely simple; so simple that I can just quote the entire thing (sans comments, license etc. - have a look at the actual source for the license):

#include <semaphore.h>
#include <fcntl.h>

class Semaphore {
public:
    Semaphore(char name[], unsigned int val);
    int wait() { return sem_wait(sem); }
    int post() { return sem_post(sem); }
    int tryWait() { return sem_trywait(sem); }
    void close() { sem_close(sem); sem_unlink(name); }

private:
    sem_t* sem;
    char* name;
};

Semaphore::Semaphore(char name[], unsigned int val)
{
    sem_unlink(name);
    this->name = name;
    this->sem = sem_open(name, O_CREAT | O_EXCL, 0666, val);
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.