I received an interesting piece of code during my recent discussion about the blocking queue: a fast semaphore implementation. The fast_semaphore class uses a regular C++ semaphore as fallback for waiting and unblocking the thread(s) while doing its magic using an atomic variable and memory fences of the new C++ memory model (see here and here).

I present to you, my shortened version of, Fast-Semaphore by Joe Seigh; C++ Implementation by Chris Thomasson:

4 Replies to “Fast semaphore”

  1. Being your semaphore is a full acq-rel cycle (as the underlying mutex locks & unlocks), you can presumably simplify to the following.

  2. Yes, that works fine. I have a habit using the standalone fences wrt my work on the SPARC. Here is an interesting discussion:

    https://groups.google.com/d/topic/lock-free/A1nzcMBGRzU/discussion

    ;^)

    Btw, this exact algorithm can be found here:

    https://www.haiku-os.org/legacy-docs/benewsletter/Issue1-26.html

    I first learned about it from Joe Seigh who worked for IBM in the 80’s and 90’s. Not exactly sure if he helped with the Benaphore.

  3. Thanks for this nice semaphore implementation, I come back time to time when I need something similar. I am wondering what do you think: is it possible to extend this technique to implement binary or counting semaphores without locking in all cases? I am not sure…

Leave a Reply