2010-03-12 9 views
1

다음 문제로 인해 제 머리카락을 당깁니다. 을 boost.interprocess 문서에 입력하여 공유 메모리에 쓴 고정 크기 링 버퍼 버퍼 클래스를 인스턴스화했습니다. 내 클래스의 골격 생성자는 다음과 같습니다공유 메모리에 사용자 정의 할당자를 사용하여 클래스를 인스턴스화합니다.

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 개체의 배열 (아마도 동적)을 만들어야합니다.

이렇게하면 마지막 문장의 템플릿과 관련된 모든 종류의 컴파일 오류가 발생합니다. 내가 도대체 ​​뭘 잘못하고있는 겁니까?

실제 오류에 대해 알지 못해서 말하기 어렵습니다. 또한 코드를 이해합니까 (Boost::Interprocess 또는 할당자가 작동하는 방법)?

예를 들어 인용하면 vector이 생성되며 포함 된 개체에 대해 인접한 메모리가 보장됩니다. 유일한 차이점은 객체가 자유 저장소가 아닌 공유 메모리 세그먼트에서 생성된다는 점입니다. 이는 할당자를 두 번째 매개 변수로 지정하지 않고 기본 할당자가 사용되는 경우 일반적으로 발생합니다.

+0

답장을 보내 주셔서 감사합니다. 제공된 할당자를 사용하여 BufferNode 객체의 배열을 만들려면 어떻게해야합니까? 나는 boost.interprocess와 예제가 희박하다는 것에 조금 불안정하다는 것을 인정해야한다. – recipriversexclusion

+0

또는 버퍼 내에 BufferNodes를 저장하는 벡터를 만드는 것이 더 좋을까요? – recipriversexclusion

+0

'deque '(또는 최소한 벡터 ')을 사용하고'SharedMemoryBuffer'를 사용하여이 구현 세부 사항을 숨길 것이라고 말하고 싶습니다. 컨테이너의 최종 선택은 필요에 따라 다릅니다. – dirkgently