我正在尝试将std :: pair添加到共享内存队列中。这不会编译。
将std :: pair添加到共享内存队列的正确方法是什么?
#include <boost/lockfree/spsc_queue.hpp> // ring buffer
#include <boost/interprocess/managed_shared_memory.hpp>
#include <boost/interprocess/allocators/allocator.hpp>
#include <boost/interprocess/containers/string.hpp>
namespace bip = boost::interprocess;
namespace shm
{
typedef bip::allocator<char, bip::managed_shared_memory::segment_manager> char_alloc;
typedef bip::basic_string<char, std::char_traits<char>, char_alloc > shared_string;
typedef boost::lockfree::spsc_queue<
shared_string,
boost::lockfree::capacity<200>
> ring_buffer;
}
#include <unistd.h>
// Ringbuffer fully constructed in shared memory. The element std::pair are
// also allocated from the same shared memory segment.
shm::ring_buffer *queue;
int main()
{
// create segment and corresponding allocator
bip::managed_shared_memory segment(bip::open_or_create, "MySharedMemory", 65536);
typedef std::pair<float, float> ValueType;
typedef bip::allocator<ValueType, bip::managed_shared_memory::segment_manager>
ShmemAllocator;
//Initialize the shared memory STL-compatible allocator
ShmemAllocator pair_alloc (segment.get_segment_manager());
queue = segment.find_or_construct<shm::ring_buffer>("queue")();
for (int i = 0; i < 3; i++)
{
//Do I really need a pointer to shared memory?
ValueType *reading = segment.construct<ValueType>
("Sensor Pacific") //name of the object
(57.3, 57.8); //ctor first argument
queue->push(reading); // THIS_FAILS_TO_COMPILE
}
}
我也试过
ValueType t = std::make_pair<float, float>(57.3, 57.8);
queue->push(ShmemAllocator(t, pair_alloc));
如果我改变了队列的类型,它也不起作用:
shm::ring_buffer<ValueType> *queue;
我知道我需要修改下面这部分代码,以便queue
的类型为shared_std_pair
,而不是shared_string
,但不知道该怎么做。得到我的部分是typedef bip::basic_string<char, std::char_traits<char>, char_alloc > shared_string
我需要shared_std_pair
namespace shm
{
typedef bip::allocator<char, bip::managed_shared_memory::segment_manager> char_alloc;
typedef bip::basic_string<char, std::char_traits<char>, char_alloc > shared_string;
typedef boost::lockfree::spsc_queue<
shared_string,
boost::lockfree::capacity<200>
> ring_buffer;
}
感觉我必须使用std::uses_allocator<std::tuple>
这样的内容,但我不会看到std::pair
的内容。