Tech Showcase

One short C++ concept a day, with examples — mostly performance, concurrency, and the hardware underneath.

← back to home
Fri · Dec 4, 2026Memory pool with an intrusive free list›

This pool grabs one big chunk of memory up front and chops it into equal blocks. The free blocks are linked into a list — and here's the neat part: each free block stores the pointer to the next one inside itself. So allocating and freeing are both just a couple of pointer moves: O(1), with no extra bookkeeping memory at all.

#include <iostream>
#include <cstddef>
#include <algorithm>

class SimpleMemoryPool {
private:
    struct Node {
        Node* next;
    };

    char* m_pool;
    Node* m_free_list;
    size_t m_block_size;
    size_t m_num_blocks;

public:
    SimpleMemoryPool(size_t block_size, size_t num_blocks)
        : m_block_size(std::max(block_size, sizeof(Node))),
          m_num_blocks(num_blocks)
    {
        // 1. Allocate a single contiguous block of raw memory
        m_pool = new char[m_block_size * m_num_blocks];

        // 2. Link all blocks together into a free list
        m_free_list = reinterpret_cast<Node*>(m_pool);
        Node* current = m_free_list;

        for (size_t i = 0; i < m_num_blocks - 1; ++i) {
            Node* next_node = reinterpret_cast<Node*>(m_pool + (i + 1) * m_block_size);
            current->next = next_node;
            current = next_node;
        }
        current->next = nullptr;
    }

    ~SimpleMemoryPool() {
        delete[] m_pool;
    }

    // Prevent copying
    SimpleMemoryPool(const SimpleMemoryPool&) = delete;
    SimpleMemoryPool& operator=(const SimpleMemoryPool&) = delete;

    // O(1) Allocation
    void* allocate() {
        if (!m_free_list) {
            return nullptr; // Out of memory
        }
        Node* node = m_free_list;
        m_free_list = m_free_list->next;
        return node;
    }

    // O(1) Deallocation
    void deallocate(void* ptr) {
        if (!ptr) return;

        Node* node = static_cast<Node*>(ptr);
        node->next = m_free_list;
        m_free_list = node;
    }
};

Caveats

  • Never pass num_blocks = 0. The setup loop counts up to num_blocks - 1, and since that's an unsigned number, 0 − 1 wraps around to an enormous value — the constructor then writes all over memory it doesn't own. Check it.
  • The block size is rounded up enough to hold a pointer, but not to any alignment boundary. The chunk itself starts out aligned, but if the block size isn't a multiple of the alignment, every block after the first sits slightly off. Round the block size up to a multiple of alignof(std::max_align_t).
  • deallocate() believes whatever pointer you hand it. Free the same block twice, or pass in a pointer that never came from this pool, and the free list gets a loop in it — the same block can then be handed out twice. Validating pointers in debug builds is worth it.
  • It's not thread-safe. Two threads allocating at the same time race on the head of the free list. Either add a lock or give each thread its own pool.
  • You get raw memory back — no constructors run, and nothing is destroyed when you free. If you're storing objects, that means placement new and a manual destructor call, and forgetting either one is undefined behavior.
  • When the pool runs dry it returns nullptr. That's a fine policy, but it means every caller has to check, every single time.

Key takeaways

  • Storing the free list inside the free blocks costs zero extra memory, and the allocator's own data is always right where it's needed.
  • One big allocation up front means no fragmentation and no surprises from the system allocator later. Allocation takes the same tiny amount of time, every time — which is exactly why pools turn up in hot paths.
  • A free block must be at least big enough to hold a pointer, because that's where its “next” lives. That's where the minimum block size of sizeof(void*) comes from.
Thu · Dec 3, 2026Asynchronous pub-sub channel›

Publishers throw events into a queue and get on with their day. One dispatcher thread takes events off the queue, grabs the list of subscribers for that channel, and calls them. Publishers never run subscriber code, and a slow subscriber doesn't slow down publishing.

#include <iostream>
#include <string>
#include <unordered_map>
#include <vector>
#include <functional>
#include <thread>
#include <queue>
#include <mutex>
#include <condition_variable>
#include <future>

template <typename MessageType>
class AsyncPubSubChannel {
public:
    using Callback = std::function<void(const MessageType&)>;
    using SubscriptionId = std::size_t;

    AsyncPubSubChannel() : stop_(false) {
        // Start the background worker thread for event loop dispatching
        worker_ = std::thread(&AsyncPubSubChannel::processQueue, this);
    }

    ~AsyncPubSubChannel() {
        {
            std::lock_guard<std::mutex> lock(queue_mutex_);
            stop_ = true;
        }
        cv_.notify_all();
        if (worker_.joinable()) {
            worker_.join();
        }
    }

    // Subscribe to a specific channel
    SubscriptionId subscribe(const std::string& channel, Callback callback) {
        std::lock_guard<std::mutex> lock(subscribers_mutex_);
        SubscriptionId id = next_id_++;
        subscribers_[channel].push_back({id, callback});
        return id;
    }

    // Unsubscribe using the ID returned upon subscription
    bool unsubscribe(const std::string& channel, SubscriptionId id) {
        std::lock_guard<std::mutex> lock(subscribers_mutex_);
        auto it = subscribers_.find(channel);
        if (it == subscribers_.end()) return false;

        auto& list = it->second;
        for (auto listIt = list.begin(); listIt != list.end(); ++listIt) {
            if (listIt->id == id) {
                list.erase(listIt);
                return true;
            }
        }
        return false;
    }

    // Non-blocking publish: pushes message to queue and returns immediately
    void publish(const std::string& channel, const MessageType& message) {
        {
            std::lock_guard<std::mutex> lock(queue_mutex_);
            event_queue_.push({channel, message});
        }
        cv_.notify_one();
    }

private:
    struct Subscriber {
        SubscriptionId id;
        Callback callback;
    };

    struct Event {
        std::string channel;
        MessageType message;
    };

    // Background loop processing queued events
    void processQueue() {
        while (true) {
            Event event;
            {
                std::unique_lock<std::mutex> lock(queue_mutex_);
                cv_.wait(lock, [this] { return stop_ || !event_queue_.empty(); });

                if (stop_ && event_queue_.empty()) return;

                event = std::move(event_queue_.front());
                event_queue_.pop();
            }

            // Dispatch callbacks asynchronously on separate thread-pool tasks
            std::vector<Callback> callbacks_to_run;
            {
                std::lock_guard<std::mutex> lock(subscribers_mutex_);
                auto it = subscribers_.find(event.channel);
                if (it != subscribers_.end()) {
                    for (const auto& sub : it->second) {
                        callbacks_to_run.push_back(sub.callback);
                    }
                }
            }

            for (const auto& cb : callbacks_to_run) {
                // Execute each callback without blocking the event worker
                std::async(std::launch::async, cb, event.message);
            }
        }
    }

    std::unordered_map<std::string, std::vector<Subscriber>> subscribers_;
    SubscriptionId next_id_{1};
    std::mutex subscribers_mutex_;

    std::queue<Event> event_queue_;
    std::mutex queue_mutex_;
    std::condition_variable cv_;
    std::thread worker_;
    bool stop_;
};

// Example Usage
int main() {
    AsyncPubSubChannel<std::string> bus;

    bus.subscribe("sports", [](const std::string& msg) {
        std::this_thread::sleep_for(std::chrono::milliseconds(200)); // Simulate work
        std::cout << "[Sports Sub 1] Processed on thread "
                  << std::this_thread::get_id() << ": " << msg << '\n';
    });

    bus.subscribe("sports", [](const std::string& msg) {
        std::cout << "[Sports Sub 2] Processed on thread "
                  << std::this_thread::get_id() << ": " << msg << '\n';
    });

    // Main thread publishes without blocking
    std::cout << "[Main] Publishing to 'sports'..." << std::endl;
    bus.publish("sports", "Touchdown scored!");
    std::cout << "[Main] Publish returned immediately." << std::endl;

    // Allow time for asynchronous execution before main exits
    std::this_thread::sleep_for(std::chrono::milliseconds(500));
    return 0;
}

Caveats

  • Watch out for the std::async calls — they're not as async as they look. The future it returns is destroyed right away, and a future from launch::async waits in its destructor until the task is done. So the dispatcher actually sits and waits for each callback to finish. If you want real fire-and-forget, use a thread pool.
  • The queue has no size limit. If publishers are faster than subscribers, it just keeps growing until you run out of memory. Real systems pick a limit and a rule: block the publisher, drop the oldest, or drop the newest.
  • Events go in first-in-first-out, but since callbacks run at the same time on different threads, they can finish in any order.
  • If a callback throws, nobody finds out — the exception lands in a future that nobody reads.
  • On shutdown, the dispatcher finishes whatever is left in the queue before it exits. That's polite, but slow callbacks will keep your program alive longer than you might expect.

Key takeaways

  • A queue plus one dispatcher thread is the classic way to decouple publishers from subscribers. Publishing stays cheap, and all the delivery logic lives in one place.
  • Copy the subscriber list while holding the lock, then make the calls after you've let go of it. That way, unsubscribing mid-delivery can't break anything.
  • Never treat std::async as fire-and-forget. Its future blocks when it's destroyed, so it quietly turns into synchronous code.
  • “Async” by itself isn't a design. Write down your limits and your ordering promises.
Wed · Dec 2, 2026Periodic callback scheduler›

This class runs your callbacks over and over at set intervals, all on one background thread. Tasks sit in a min-heap sorted by when they run next. The worker sleeps until the top task is due, runs it, and puts it back with a new deadline. Cancelling is lazy: deschedule() just writes the id down, and the task gets dropped when it reaches the top of the heap.

#include <iostream>
#include <chrono>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <queue>
#include <unordered_set>
#include <functional>

class Scheduler {
public:
    using Clock = std::chrono::steady_clock;

    Scheduler() : worker_(&Scheduler::run, this) {}

    ~Scheduler() {
        {
            std::lock_guard<std::mutex> lock(mutex_);
            running_ = false;
        }
        cv_.notify_one();
        if (worker_.joinable()) worker_.join();
    }

    int schedule(std::chrono::milliseconds interval, std::function<void()> cb) {
        std::lock_guard<std::mutex> lock(mutex_);
        int id = ++next_id_;
        pq_.push({Clock::now() + interval, interval, cb, id});
        cv_.notify_one();
        return id;
    }

    void deschedule(int id) {
        std::lock_guard<std::mutex> lock(mutex_);
        cancelled_.insert(id);
    }

private:
    struct Task {
        Clock::time_point next;
        std::chrono::milliseconds interval;
        std::function<void()> cb;
        int id;

        // Min-heap comparator (earliest time at top)
        bool operator>(const Task& other) const { return next > other.next; }
    };

    void run() {
        std::unique_lock<std::mutex> lock(mutex_);
        while (running_) {
            if (pq_.empty()) {
                cv_.wait(lock, [this] { return !running_ || !pq_.empty(); });
            } else {
                auto top = pq_.top();

                // Skip cancelled tasks lazily
                if (cancelled_.count(top.id)) {
                    pq_.pop();
                    cancelled_.erase(top.id);
                    continue;
                }

                if (cv_.wait_until(lock, top.next) == std::cv_status::timeout) {
                    pq_.pop();

                    // Run callback outside lock
                    lock.unlock();
                    top.cb();
                    lock.lock();

                    // Reschedule for periodic execution
                    top.next = Clock::now() + top.interval;
                    pq_.push(top);
                }
            }
        }
    }

    int next_id_ = 0;
    bool running_ = true;
    std::priority_queue<Task, std::vector<Task>, std::greater<Task>> pq_;
    std::unordered_set<int> cancelled_;
    std::mutex mutex_;
    std::condition_variable cv_;
    std::thread worker_;
};

Caveats

  • It's fixed-delay, not fixed-rate. The next run is set to “now + interval” after the callback finishes, so the real gap between runs is the interval plus however long the callback took — and over time it drifts. If you need things to fire on a steady beat, keep adding the interval to the old deadline instead, and decide what to do when you fall behind.
  • One worker thread means one slow callback holds up everything behind it.
  • If a callback throws, the exception escapes the worker loop and kills the program. Wrap the call in try/catch in real code.
  • Cancelling a task while it's running doesn't stop that run. It still gets rescheduled once, and the cancellation only takes effect when that next run reaches the top of the heap.
  • A cancelled id is only cleaned up when its task reaches the top. Cancel a task with a one-hour interval and its id sits in the set for up to an hour. Harmless, but worth knowing.

Key takeaways

  • A priority queue plus wait_until is the standard way to build a timer. No polling, no busy-waiting.
  • Lazy deletion beats digging elements out of the middle of a heap. Just mark the id and skip it later.
  • Always run callbacks without holding the lock. Otherwise nothing can schedule or cancel during a callback — and a callback that tries to schedule something would deadlock.
  • Use steady_clock for anything interval-based. It never jumps around when the system clock gets adjusted.
Tue · Dec 1, 2026Thread-safe circular buffer›

This is a fixed-size ring buffer that lets producer and consumer threads hand work to each other safely. push() and pop() wait when the buffer is full or empty. If you'd rather not wait, try_push() and try_pop() return right away. One mutex protects everything, and there are two condition variables — one for “not full”, one for “not empty” — so producers and consumers sleep in separate queues.

#include <mutex>
#include <condition_variable>
#include <vector>
#include <cstddef>
#include <utility>
#include <optional>

template <typename T>
class ThreadSafeCircularBuffer {
private:
    std::vector<T> buffer_;
    const std::size_t capacity_;
    std::size_t head_ = 0; // Index for next pop
    std::size_t tail_ = 0; // Index for next push
    std::size_t size_ = 0; // Current count of elements

    mutable std::mutex mtx_;
    std::condition_variable cv_not_full_;
    std::condition_variable cv_not_empty_;

public:
    explicit ThreadSafeCircularBuffer(std::size_t capacity)
        : buffer_(capacity), capacity_(capacity) {}

    // Disable copy/move semantics to prevent concurrency hazards
    ThreadSafeCircularBuffer(const ThreadSafeCircularBuffer&) = delete;
    ThreadSafeCircularBuffer& operator=(const ThreadSafeCircularBuffer&) = delete;

    // Blocking Push (Producer)
    void push(T item) {
        std::unique_lock<std::mutex> lock(mtx_);
        // Wait until there is space in the buffer
        cv_not_full_.wait(lock, [this] { return size_ < capacity_; });

        buffer_[tail_] = std::move(item);
        tail_ = (tail_ + 1) % capacity_;
        ++size_;

        // Unlock before notifying to reduce lock contention on the woken thread
        lock.unlock();
        cv_not_empty_.notify_one();
    }

    // Blocking Pop (Consumer)
    T pop() {
        std::unique_lock<std::mutex> lock(mtx_);
        // Wait until there is data available
        cv_not_empty_.wait(lock, [this] { return size_ > 0; });

        T item = std::move(buffer_[head_]);
        head_ = (head_ + 1) % capacity_;
        --size_;

        lock.unlock();
        cv_not_full_.notify_one();
        return item;
    }

    // Non-blocking try_push (returns immediately if full)
    bool try_push(T item) {
        std::unique_lock<std::mutex> lock(mtx_);
        if (size_ == capacity_) {
            return false;
        }

        buffer_[tail_] = std::move(item);
        tail_ = (tail_ + 1) % capacity_;
        ++size_;

        lock.unlock();
        cv_not_empty_.notify_one();
        return true;
    }

    // Non-blocking try_pop (returns std::nullopt if empty)
    std::optional<T> try_pop() {
        std::unique_lock<std::mutex> lock(mtx_);
        if (size_ == 0) {
            return std::nullopt;
        }

        T item = std::move(buffer_[head_]);
        head_ = (head_ + 1) % capacity_;
        --size_;

        lock.unlock();
        cv_not_full_.notify_one();
        return item;
    }

    std::size_t size() const {
        std::lock_guard<std::mutex> lock(mtx_);
        return size_;
    }

    bool empty() const {
        std::lock_guard<std::mutex> lock(mtx_);
        return size_ == 0;
    }
};

Caveats

  • Don't build one with capacity 0. It can never hold anything: push() waits forever, try_push() always fails, and the wrap-around math stops making sense. Check the capacity in the constructor.
  • pop() moves the value out of its slot but leaves the moved-from object sitting there until something overwrites it. Harmless in practice — just don't assume slots are ever really “empty”.
  • head_, tail_ and size_ all get updated under the same mutex, so they end up sharing a cache line that keeps bouncing between the producer's and the consumer's cores, even though the threads are touching different variables. Padding these counters onto separate cache lines genuinely speeds this class up.
  • There's no way to shut it down. A thread waiting in push() or pop() waits forever, so a real-world version needs a close() flag that wakes everybody up.
  • It's correct, just not lock-free. Every operation queues up on the one mutex. If contention becomes the bottleneck, the next step is a lock-free ring buffer built for your producer/consumer count.

Key takeaways

  • Always give wait() a predicate. It saves you from spurious wakeups, which do happen.
  • Keeping an explicit size_ count is what tells “full” apart from “empty” — when head_ equals tail_ you can't tell otherwise. (The usual alternative is wasting one slot.)
  • Unlock before you notify. Otherwise the thread you just woke up immediately blocks on the mutex you're still holding.
  • Delete the copy constructor and assignment. Copying a mutex and two condition variables is never what you want.