【发布时间】:2011-01-07 00:51:20
【问题描述】:
我在多线程应用程序中为 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 对象之间共享池。
【问题讨论】:
-
我知道你已经选择了一个答案。但是...如果这是 Windows,请查看 Microquill 的 SmartHeap 或 HeapAgent。这是我测试或用于此类问题的最佳插件库。不,我不隶属于他们。
标签: c++ multithreading memory-management