2010-03-12 58 views
1

我拉我的頭髮由於下面的問題:我下面Boost.Interprocess中文檔中給出the example實例,我在共享內存中寫了一個固定大小的環形緩衝區緩存類。我的課的骨架構造是:實例化類的共享內存自定義分配器

template<typename ItemType, class Allocator > 
SharedMemoryBuffer<ItemType, Allocator>::SharedMemoryBuffer(unsigned long capacity){ 

    m_capacity = capacity; 

    // Create the buffer nodes. 
    m_start_ptr = this->allocator->allocate(); // allocate first buffer node 
    BufferNode* ptr = m_start_ptr; 
    for(int i = 0 ; i < this->capacity()-1; i++) { 
     BufferNode* p = this->allocator->allocate(); // allocate a buffer node 
    } 
} 

我的第一個問題:請問這種分配保證緩衝區節點在連續存儲單元,即分配的,當我嘗試從地址m_start_ptr + n*sizeof(BufferNode)訪問的第n個節點在我的Read()方法會起作用嗎?如果沒有,保留節點,創建鏈表的更好方法是什麼?

我的測試工具如下:

// Define an STL compatible allocator of ints that allocates from the managed_shared_memory. 
// This allocator will allow placing containers in the segment 
typedef allocator<int, managed_shared_memory::segment_manager> ShmemAllocator; 

//Alias a vector that uses the previous STL-like allocator so that allocates 
//its values from the segment 
typedef SharedMemoryBuffer<int, ShmemAllocator> MyBuf; 

int main(int argc, char *argv[]) 
{ 
    shared_memory_object::remove("MySharedMemory"); 

    //Create a new segment with given name and size 
    managed_shared_memory segment(create_only, "MySharedMemory", 65536); 

    //Initialize shared memory STL-compatible allocator 
    const ShmemAllocator alloc_inst (segment.get_segment_manager()); 

    //Construct a buffer named "MyBuffer" in shared memory with argument alloc_inst 
    MyBuf *pBuf = segment.construct<MyBuf>("MyBuffer")(100, alloc_inst); 
} 

這給了我各種有關模板的最後一條語句編譯錯誤。我究竟做錯了什麼? segment.construct<MyBuf>("MyBuffer")(100, alloc_inst)是提供兩個模板參數的正確方法嗎?

回答

1

我的第一個問題:這是否有點 分配保證緩衝 節點在連續 存儲位置分配,即當我嘗試 訪問從地址 m_start_ptr第n個節點+ N *的sizeof (BufferNode) 我的Read()方法會工作嗎?

號的原因是,你只需要在第一個節點。您創建的所有BufferNode對象都未保存(例如,以鏈接列表方式)並導致內存泄漏。此外,這種分配方式不保證連續的存儲位置。隨機訪問(就像你在後面提到的那樣)很可能會失敗。要獲得連續的內存,您需要創建一個數組(可能是動態的)BufferNode對象。

這給了我最後一條語句的模板相關的各種編譯錯誤。我究竟做錯了什麼?

很難說清楚,無需瞭解實際的錯誤。此外,你是否理解你的代碼(以及如何適應分配器的工作方式)?

注意,你舉的例子創建這是保證有連續的存儲器,用於其包含的對象一個vector。唯一的區別在於,對象是在共享內存段上創建的,而不是通常在您沒有將分配器指定爲第二個參數並使用默認值時發生的免費存儲區。

+0

感謝您的回覆。我怎樣才能使用提供的分配器創建一個BufferNode對象的數組?我必須承認,我對boost.interprocess有點不穩定,例子很少。 – recipriversexclusion 2010-03-12 23:33:55

+0

或者,創建一個向量來緩衝區內存儲BufferNode會更好嗎? – recipriversexclusion 2010-03-12 23:35:28

+0

我會說使用'雙端隊列'(或至少是一個矢量''),並有'SharedMemoryBuffer'這個隱藏實現細節。容器的最終選擇取決於您的需求。 – dirkgently 2010-03-12 23:57:29