我在使用多线程应用时,使用池化内存分配器来为std::list对象分配内存时遇到了一些问题。
我关注的代码部分是每个线程函数独立运行(即没有线程之间的通信或同步),因此我想为每个线程设置单独的内存池,其中每个池都不是线程安全的(因此速度更快)。
我尝试使用共享的线程安全单例内存池,但发现性能很差,这是预料中的。
这是我正在尝试做的事情类型的大大简化版本。伪代码方式包含了很多内容,如果有点混乱请见谅。
我关注的代码部分是每个线程函数独立运行(即没有线程之间的通信或同步),因此我想为每个线程设置单独的内存池,其中每个池都不是线程安全的(因此速度更快)。
我尝试使用共享的线程安全单例内存池,但发现性能很差,这是预料中的。
这是我正在尝试做的事情类型的大大简化版本。伪代码方式包含了很多内容,如果有点混乱请见谅。
/* The thread functor - one instance of MAKE_QUADTREE created for each thread
*/
class make_quadtree
{
private:
/* A non-thread-safe memory pool for int linked list items, let's say that it's
* something along the lines of BOOST::OBJECT_POOL
*/
pooled_allocator<int> item_pool;
/* The problem! - a local class that would be constructed within each std::list as the
* allocator but really just delegates to ITEM_POOL
*/
class local_alloc
{
public :
//!! I understand that I can't access ITEM_POOL from within a nested class like
//!! this, that's really my question - can I get something along these lines to
//!! work??
pointer allocate (size_t n) { return ( item_pool.allocate(n) ); }
};
public :
make_quadtree (): item_pool() // only construct 1 instance of ITEM_POOL per
// MAKE_QUADTREE object
{
/* The kind of data structures - vectors of linked lists
* The idea is that all of the linked lists should share a local pooled allocator
*/
std::vector<std::list<int, local_alloc>> lists;
/* The actual operations - too complicated to show, but in general:
*
* - The vector LISTS is grown as a quadtree is built, it's size is the number of
* quadtree "boxes"
*
* - Each element of LISTS (each linked list) represents the ID's of items
* contained within each quadtree box (say they're xy points), as the quadtree
* is grown a lot of ID pop/push-ing between lists occurs, hence the memory pool
* is important for performance
*/
}
};
我的问题实际上是,我希望每个线程函数对象都有一个内存池实例,但在每个线程函数中,多个std::list对象之间共享该内存池。