Click here to Skip to main content
15,357,358 members
Articles / General Programming / Threads
Posted 15 Mar 2019

Tagged as



Fast Semaphore

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
15 Mar 2019MIT
Fast semaphore

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:

#pragma once

#include <mutex>
#include <atomic>
#include <condition_variable>
#include <cassert>

class semaphore
    semaphore(int count) noexcept
    : m_count(count) { assert(count > -1); }

    void post() noexcept
            std::unique_lock<std::mutex> lock(m_mutex);

    void wait() noexcept
        std::unique_lock<std::mutex> lock(m_mutex);
        m_cv.wait(lock, [&]() { return m_count != 0; });

    int m_count;
    std::mutex m_mutex;
    std::condition_variable m_cv;

class fast_semaphore
    fast_semaphore(int count) noexcept
    : m_count(count), m_semaphore(0) {}

    void post()
        int count = m_count.fetch_add(1, std::memory_order_relaxed);
        if (count < 0)

    void wait()
        int count = m_count.fetch_sub(1, std::memory_order_relaxed);
        if (count < 1)

    std::atomic<int> m_count;
    semaphore m_semaphore;
This article was originally posted at


This article, along with any associated source code and files, is licensed under The MIT License


About the Author

Martin Vorbrodt
Software Developer (Senior)
United States United States
No Biography provided

Comments and Discussions

Questionmhm Pin
Goran Mitrovic15-Mar-19 13:56
MemberGoran Mitrovic15-Mar-19 13:56 
For fast_semaphore to be fast, conditional_variable needs to be fast. Is conditional_variable fast?

If you do wait() on one thread and while if(count<1) is executing, you do post() on the other thread, your fast_semaphore will fail as conditional_variable notification will be lost if noone is listening (such a terrible design)...
- Goran.

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.