While planning to modernize our in-house HTS program's architecture around Direct2D and multi-core parallel processing, the issue I agonized over the most was the "bottleneck in the data pipeline."
A massive volume of real-time market data has to be picked up simultaneously by multiple screen components and rendered on screen. If, as before, each screen were to build its own copy of the data structure in memory, CPU usage would inevitably spike and rendering speed would suffer.
As a solution, I designed a zero-copy approach where the Data Manager (running on a sub-thread) centrally manages static memory, while each screen (running on the UI thread) simply references that memory address. However, the synchronization and safety issues that arise when writes and reads happen concurrently in a multithreaded environment held me back.
In this post, I document the process I went through to solve this problem β starting with double buffering, moving on to triple buffering, and finally arriving at what I consider the ideal architecture: "std::shared_ptr + a custom deleter + an object pool."
1. Lock Contention and the Limits of Traditional Synchronization
The simplest approach is to use a Mutex or a Critical Section. But in an environment where prices update thousands of times per second, locking every time a screen reads data forces the writer thread (the Data Manager) to block and wait. Conversely, when the writer thread updates the data, screen rendering comes to a halt.
You could use an SRWLock for a read-heavy environment, but to eliminate lock overhead at the root, a lock-free structure was necessary.
2. The Light and Shadow of Double Buffering
The first thing that came to mind for eliminating locks was double buffering, a technique commonly used in graphics rendering.
- Keep struct A (for reading) and struct B (for writing).
- The Data Manager writes data into the idle buffer B, and once it's done, atomically swaps the pointer from A to B.
This is very fast and elegant, but it carried a high risk of tearing. While the UI thread is reading data and drawing it (say, taking 5ms), the Data Manager might receive two or more new price updates in the meantime, eventually flipping even the memory the UI is currently reading back into write mode and overwriting it.
3. Triple Buffering and Its Conflict with a Multi-Screen Environment
To solve double buffering's overwrite problem, I considered triple buffering. This splits the buffer into three (Read, Write, Ready), fully decoupling the wait times of the reader and writer threads.
By using std::atomic's exchange operation to swap the three indices, you get a perfectly lock-free implementation. The Data Manager keeps pushing the latest data into the 'Ready' buffer without waiting on the UI, and the UI simply grabs the finished contents of the 'Ready' buffer once per screen-refresh cycle.
Triple buffering is flawless in a 1:1 (one producer, one consumer) setup, but it simply couldn't be used in an environment like our HTS, where multiple screens (UIs) pick up data at the same time. If Screen A and Screen B are each holding onto a different past buffer, the Data Manager runs out of free buffers to write the next piece of data into, and the whole structure breaks down completely.
4. The Ultimate Architecture: std::shared_ptr + Custom Deleter + Object Pool
To resolve all of these dilemmas at once β lock overhead, keeping references alive across multiple screens, and preventing memory fragmentation β the final architecture I adopted combines smart pointers from the modern C++ standard with a memory pool.
1. Object Pool (static memory pool): At program startup, thousands of structs to hold market data are pre-allocated in memory. Since the OS heap manager is never touched, allocation overhead is zero.
2. Virtual double buffering (snapshot): When new market data arrives, the Data Manager pulls an empty struct from the pool and writes the data into it, then atomically swaps the global pointer.
3. Reference counting: Right before rendering, the UI screen loads (copies) this pointer as a
shared_ptr. Since the reference count goes up by 1, even if the sub-thread updates the data hundreds or thousands of times, the memory the UI is holding is never overwritten.4. Custom Deleter (automatic return): When the UI screen finishes rendering and the
shared_ptr is destroyed, a lambda function is injected so that instead of calling delete on the memory, it is automatically returned to the Object Pool.
#include <iostream>
#include <memory>
#include <atomic>
#include <vector>
#include <mutex>
#include <string>
// 1. Market data struct
struct MarketData {
std::string code;
int price;
long volume;
void Reset() { code.clear(); price = 0; volume = 0; }
};
// 2. Thread-safe object pool
class MarketDataPool {
private:
std::vector<MarketData*> m_pool;
std::mutex m_mutex;
public:
MarketDataPool(size_t initialSize) {
for (size_t i = 0; i < initialSize; ++i) {
m_pool.push_back(new MarketData());
}
}
~MarketDataPool() { for (auto ptr : m_pool) delete ptr; }
MarketData* Acquire() {
std::lock_guard<std::mutex> lock(m_mutex);
if (m_pool.empty()) return new MarketData();
MarketData* ptr = m_pool.back();
m_pool.pop_back();
return ptr;
}
void Release(MarketData* ptr) {
if (!ptr) return;
ptr->Reset();
std::lock_guard<std::mutex> lock(m_mutex);
m_pool.push_back(ptr);
}
};
// 3. Manager class that centrally manages the data
class DataManager {
private:
MarketDataPool m_pool;
std::atomic<std::shared_ptr<MarketData>> m_latestData;
public:
DataManager() : m_pool(1000) {
MarketData* rawPtr = m_pool.Acquire();
auto initData = std::shared_ptr<MarketData>(rawPtr, [this](MarketData* p) {
m_pool.Release(p);
});
m_latestData.store(initData);
}
// [Sub-thread region] Receive and record market data
void OnReceiveNewData(const std::string& code, int price, long volume) {
MarketData* rawPtr = m_pool.Acquire();
rawPtr->code = code;
rawPtr->price = price;
rawPtr->volume = volume;
// Inject the custom deleter: return to the pool once the ref count hits 0
auto newData = std::shared_ptr<MarketData>(rawPtr, [this](MarketData* p) {
m_pool.Release(p);
});
// Atomically swap the global pointer (lock-free)
m_latestData.store(newData);
}
// [UI-thread region] Fetch a snapshot for the screen
std::shared_ptr<MarketData> GetSnapshot() {
return m_latestData.load();
}
};
5. A Detailed Look at the Custom Deleter
auto newData = std::shared_ptr<MarketData>(rawPtr, [this](MarketData* p) {
m_pool.Release(p);
});
When constructing the std::shared_ptr, we're passing two arguments inside the parentheses ( ).
- First argument:
rawPtr
β’ What it is: The "real memory address (raw pointer)" just borrowed from the Object Pool.
β’ Its role: It tells theshared_ptr, "from now on, wrap and manage this address." - Second argument:
[this](MarketData* p) { m_pool.Release(p); }
This part is the lambda function (anonymous function) that acts as the "custom deleter."
Normally, once the reference count of astd::shared_ptr(the number of screens currently reading it) hits0, it unconditionally callsdelete rawPtr;internally, returning (destroying) the memory back to the system. But by passing a function as the second argument, you intercept that default behavior β essentially telling it, "when the reference count hits 0, don't calldelete; run this function I've given you instead."
Let's break this lambda function down a bit further.
[this](capture clause): brings thethispointer of the current class (DataManager) into the lambda, so it can access the class's member variables and functions. Without this, there'd be no way to reach the memberm_pool.(MarketData* p)(parameter): when theshared_ptrreaches the end of its lifetime, it passes the real memory address it was managing (rawPtr) into this variablep.{ m_pool.Release(p); }(body): instead of destroying the received memory addresspwithdelete, it hands it off to theRelease()function of our object pool,m_pool.
In other words, that single line of code is like writing the following contract for the C++ compiler:
"I'm creating a new smart pointer,
newData, and the payload it will manage is rawPtr. Later, once every screen (UI) is done using this data and the reference count hits 0, don't ever blow the memory away with delete β hand rawPtr back to m_pool (release it) instead."Thanks to this one line, we get to hand off the pointer's lifetime to
shared_ptr's convenient automatic management, while the actual memory just keeps cycling around instead of being allocated and freed every time β completing a perfect zero-allocation system.
6. Wrapping Up
The architecture I designed this time is one that can fundamentally block the slowdowns that arise in a multi-core environment and a Direct2D rendering pipeline.
By perfectly combining the "static efficiency of the memory pool" with the "thread safety of smart pointers," I eliminated lock waits entirely and even removed the risk of dangling pointers or memory leaks. I expect this to serve as a solid backbone for the next-generation HTS data pipeline we'll be building going forward.