Использование кругового буфера на диске

Я пытался создать дисковый буфер с отображением в памяти, используя Boost, и я прочитал этот ответ: https://stackoverflow.com/a/29265629/8474732

Однако мне трудно читать циклический буфер, который был написан. Я попытался сделать push_back для переменной «instance», теперь экземпляр имеет размер 1. Отлично. Но как бы я прочитал содержимое обратно? Или push_back дополнительные элементы в более позднее время? Создание другого экземпляра из того же распределителя и mmf показывает, что экземпляр имеет размер 0. Я хотел бы функцию, которая может открыть файл на диске и push_back значение в циклическом буфере, а затем вернуть. Я хотел бы вызвать эту функцию несколько раз. Пример того, что я пытаюсь сделать (получено из связанного ответа):

#include <boost/circular_buffer.hpp>
#include <boost/interprocess/allocators/allocator.hpp>
#include <boost/interprocess/managed_mapped_file.hpp>

namespace bip = boost::interprocess;

struct message {
int data[32];
};

void writeFunction() {
bip::managed_mapped_file mmf(bip::open_or_create, "./circ_buffer.bin", 4ul << 10);
typedef bip::allocator<message, bip::managed_mapped_file::segment_manager> allocator;

boost::circular_buffer<message, allocator> instance(10, mmf.get_segment_manager());

struct message test;
instance.push_back( test );
}

Я хотел бы вызвать эту функцию, когда я хочу записать в кольцевой буфер на диске, а также иметь возможность читать ее с помощью другой функции (что-то вроде этого):

void readFunction() {
bip::managed_mapped_file mmf(bip::open_or_create, "./circ_buffer.bin", 4ul << 10);
typedef bip::allocator<message, bip::managed_mapped_file::segment_manager> allocator;

boost::circular_buffer<message, allocator> instance(10, mmf.get_segment_manager());

for(struct message msg : instance) {
cout << msg.string;
}
}

Спасибо за любую помощь!

1

Решение

Связанный пост был мимимальным примером, который ТОЛЬКО показал, что распределитель с сохранением состояния, необходимый для сегментов памяти Boost Interprocess, поддерживается в circular_buffer,

Чтобы извлечь сам циклический буфер из сегмента, вам необходимо создать сам объект в сегменте разделяемой памяти (в дополнение к передаче shared-mem-allocator).

DEMO

На эффективность не обращали внимания, это просто тупая демонстрация:

Жить на Колиру

#include <boost/circular_buffer.hpp>
#include <boost/interprocess/allocators/allocator.hpp>
#include <boost/interprocess/managed_mapped_file.hpp>
#include <iostream>

namespace bip = boost::interprocess;

struct message {
int data[32];
};

void writeFunction() {
bip::managed_mapped_file mmf(bip::open_or_create, "./circ_buffer.bin", 4ul << 10);
typedef bip::allocator<message, bip::managed_mapped_file::segment_manager> allocator;
typedef boost::circular_buffer<message, allocator> circ_buf;

auto& instance = *mmf.find_or_construct<circ_buf>("named_buffer")(10, mmf.get_segment_manager());

struct message test;
instance.push_back( test );
std::cout << "pushed a message (" << instance.size() << ")\n";
}

void readFunction() {
bip::managed_mapped_file mmf(bip::open_or_create, "./circ_buffer.bin", 4ul << 10);
typedef bip::allocator<message, bip::managed_mapped_file::segment_manager> allocator;
typedef boost::circular_buffer<message, allocator> circ_buf;

auto& instance = *mmf.find_or_construct<circ_buf>("named_buffer")(10, mmf.get_segment_manager());

struct message test;
while (!instance.empty()) {
test = instance.front();
instance.pop_front();
std::cout << "popped a message (" << instance.size() << ")\n";
}
}

int main() {
writeFunction();
writeFunction();
writeFunction();

readFunction();
}

Печать

{"a":["1","2","3","4","5","6"]}
4
4
No such node (b)
element_at_checked
1

Другие решения

Других решений пока нет …

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector