Objectpool - Object pool implementation in C++11

Overview

Object pool allocator

This is a C++11 implementation of an object pool allocator.

For more information on object pool allocators and their purpose see http://gameprogrammingpatterns.com/object-pool.html.

Both a fixed size pool (FixedObjectPool) and a dynamically growing pool (DynamicObjectPool) implementation are included.

The main features of this implementation are:

  • new_object method uses C++11 std::forward to pass construction arguments to the constructor of the new object being created in the pool
  • for_each method will iterate over all live objects in the pool calling the given function on them
  • delete_all method will free all pool objects at once, skipping the destructor call for trivial types
  • maintains a freelist of next available pool entry for fast allocation

These object pool classes are not designed with exceptions in mind as most game code avoids using exceptions.

Example usage

// some type to be pooled
struct Enemy {
/* some data */
Enemy(const char* name);
void update(double delta_time);
};

// created fixed size pool with space for 64 enemies
FixedObjectPool<Enemy> enemy_pool(64);

// allocate an enemy - construction parameters are forwarded
Enemy* baddie = enemy_pool.new_object("The Mekon");

// update all live enemies by executing the lambda on all allocated objects
enemy_pool.for_each([delta_time](Enemy* enemy)
    {
        enemy->update(delta_time);
    });

// delete a single enemy
enemy_pool.delete_object(baddie);

// delete all enemies at once (beware of dangling pointers)
enemy_pool.delete_all();

Implementation details

Both FixedObjectPool and DynamicObjectPool are implemented using the ObjectPoolBlock class.

ObjectPoolBlock is a single allocation containing the ObjectPoolBlock instance, indices of used pool entries and the pool memory itself.

Occupancy is tracked using indexes into available entries in the block for constant time allocation. The ObjectPoolBlock keeps the next free index head. This index can be used to find the next available block entry when allocating a new entry.

A separate list of indices is used to track occupancy versus reusing object pool memory for this purpose to avoid polluting CPU caches with objects which are deleted and thus no longer in use.

Unit testing

Unit tests are written using the Catch unit testing framework. Unit tests are run through the runtest executable.

Micro-benchmarking

This repository also includes bench.hpp which is a single header file micro-benchmarking framework inspired by Catch and Rust's benchmarking tests.

It's my intention to make this standalone at some point but at the moment it's very much a work in progress.

Currently each micro-benchmark compares the performance of the following:

  • Fixed pool
  • Dynamic pool with 64, 128 and 256 entry blocks
  • The default allocator

Benchmarks output nanoseconds per iteration (lower is better) and megabytes per second throughput (higher is better).

Prerequisites

The test and benchmarking applications require CMake to generate build files.

Compiling and running

To generate a build, compile and run follow these steps:

mkdir build
cd build
cmake -DCMAKE_BUILD_TYPE=Release ..
make
./runtests
./runbench

License

This software is licensed under the zlib license, see the LICENSE file for details.

You might also like...
High Performance Linux C++ Network Programming Framework based on IO Multiplexing and Thread Pool

Kingpin is a C++ network programming framework based on TCP/IP + epoll + pthread, aims to implement a library for the high concurrent servers and clie

Work Stealing Thread Pool

wstpool Work Stealing Thread Pool, Header Only, C++ Threads Consistent with the C++ async/future programming model. Drop-in replacement for 'async' fo

BabyCoin: mining pool

BabyCoin Pool Based on cryptonote-nodejs-pool cryptonote-nodejs-pool High performance Node.js (with native C addons) mining pool for CryptoNote based

MAN - Man is Thread Pool in C++17

Introduction MAN is a ThreadPool wrote in C++17. The name is chosen because, at least in France, it is said that men are not able to do several things

ThreadPool - A fastest, exception-safety and pure C++17 thread pool.

Warnings Since commit 468129863ec65c0b4ede02e8581bea682351a6d2, I move ThreadPool to C++17. (To use std::apply.) In addition, the rule of passing para

CTPL - Modern and efficient C++ Thread Pool Library

CTPL Modern and efficient C++ Thread Pool Library A thread pool is a programming pattern for parallel execution of jobs, http://en.wikipedia.org/wiki/

Design and Implementation of kernel level threads for xv6 operating system. Adding system call related to threading environment in xv6 along with userland threading library with one to one mapping and semaphore implementation as synchronisation primitive   An implementation of Actor, Publish-Subscribe, and CSP models in one rather small C++ framework. With performance, quality, and stability proved by years in the production.
An implementation of Actor, Publish-Subscribe, and CSP models in one rather small C++ framework. With performance, quality, and stability proved by years in the production.

What is SObjectizer? What distinguishes SObjectizer? SObjectizer is not like TBB, taskflow or HPX Show me the code! HelloWorld example Ping-Pong examp

Comments
  • x64 constructor func error

    x64 constructor func error

    vs2015, x64 error

    struct Node { void* p1; };
    
    int main()
    {
        FixedObjectPool<Node> pool(1);
        reutrn 0;
    }
    

    error in

    object_pool.inl
    
    ObjectPoolBlock<T>* ObjectPoolBlock<T>::create(index_t entries_per_block)
    {
    ……
    assert(reinterpret_cast<uint8_t*>(ptr->memory_begin())
                == reinterpret_cast<uint8_t*>(ptr) + header_size + indices_size);
    ……
    }
    
    opened by Klusxy 5
  • the realloc may change pointer

    the realloc may change pointer

    you use realloc to add block ,but realloc may return a pointer different from the previous, if this happen, all the allocated object pointer will be invalid. this is a serious issue. so i advise not to use realloc, but alloc a new chunk, then use lists to connect the chunks.

    opened by wiltchamberian 1
Owner
Cameron Hart
Game engine/physics programmer at Wargaming.net
Cameron Hart
Pool is C++17 memory pool template with different implementations(algorithms)

Object Pool Description Pool is C++17 object(memory) pool template with different implementations(algorithms) The classic object pool pattern is a sof

KoynovStas 1 Nov 18, 2022
Thread pool - Thread pool using std::* primitives from C++17, with optional priority queue/greenthreading for POSIX.

thread_pool Thread pool using std::* primitives from C++11. Also includes a class for a priority thread pool. Requires concepts and C++17, including c

Tyler Hardin 77 Dec 30, 2022
Thread-pool-cpp - High performance C++11 thread pool

thread-pool-cpp It is highly scalable and fast. It is header only. No external dependencies, only standard library needed. It implements both work-ste

Andrey Kubarkov 542 Dec 17, 2022
An ultra-simple thread pool implementation for running void() functions in multiple worker threads

void_thread_pool.cpp © 2021 Dr Sebastien Sikora. [email protected] Updated 06/11/2021. What is it? void_thread_pool.cpp is an ultra-simple

Seb Sikora 1 Nov 19, 2021
ThreadPool - A simple C++11 Thread Pool implementation

ThreadPool A simple C++11 Thread Pool implementation. Basic usage: // create thread pool with 4 worker threads ThreadPool pool(4); // enqueue and sto

Jakob Progsch 6.1k Jan 7, 2023
A modern thread pool implementation based on C++20

thread-pool A simple, functional thread pool implementation using pure C++20. Features Built entirely with C++20 Enqueue tasks with or without trackin

Paul T 151 Dec 22, 2022
A easy to use multithreading thread pool library for C. It is a handy stream like job scheduler with an automatic garbage collector. This is a multithreaded job scheduler for non I/O bound computation.

A easy to use multithreading thread pool library for C. It is a handy stream-like job scheduler with an automatic garbage collector for non I/O bound computation.

Hyoung Min Suh 12 Jun 4, 2022
A C++17 thread pool for high-performance scientific computing.

We present a modern C++17-compatible thread pool implementation, built from scratch with high-performance scientific computing in mind. The thread pool is implemented as a single lightweight and self-contained class, and does not have any dependencies other than the C++17 standard library, thus allowing a great degree of portability

Barak Shoshany 1.1k Jan 4, 2023
An easy to use C++ Thread Pool

mvThreadPool (This library is available under a free and permissive license) mvThreadPool is a simple to use header only C++ threadpool based on work

Jonathan Hoffstadt 30 Dec 8, 2022
EOSP ThreadPool is a header-only templated thread pool writtent in c++17.

EOSP Threadpool Description EOSP ThreadPool is a header-only templated thread pool writtent in c++17. It is designed to be easy to use while being abl

null 1 Apr 22, 2022