O'Reilly logo

Efficient C++ Performance Programming Techniques by David Mayhew, Dov Bulka

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Version 4: Implementation

Version 4 implements a multithreaded memory pool. It can handle any pool and lock type that conform to the expected interface:

template <class POOLTYPE, class LOCK>
class MTMemoryPool {
public:
    // Allocate an element from the freeList.
    inline void* alloc (size_t size);

    // Return an element to the freeList.
    inline void free (void* someElement);
private:
    POOLTYPE stPool;  // Single-threaded pool.
    LOCK      theLock;
};

The alloc() method delegates the allocation to the memory pool member, and the locking to the lock member, respectively:

 template <class M, class L> inline void* MTMemoryPool<M,L>::alloc (size_t size) { void * mem; theLock.lock(); mem = stPool.alloc(size); theLock.unlock(); return mem; } template <class M, class ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required