Skip to content

Instantly share code, notes, and snippets.

@adnils
Forked from sehe/Makefile
Created May 15, 2017 12:07
Show Gist options
  • Save adnils/7c095da88fd0562d2a6079b3d0a02754 to your computer and use it in GitHub Desktop.
Save adnils/7c095da88fd0562d2a6079b3d0a02754 to your computer and use it in GitHub Desktop.
Boost shared memory lockfree circular buffer queue
#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 <iostream>
int main()
{
// create segment and corresponding allocator
bip::managed_shared_memory segment(bip::open_or_create, "MySharedMemory", 65536);
shm::char_alloc char_alloc(segment.get_segment_manager());
shm::ring_buffer *queue = segment.find_or_construct<shm::ring_buffer>("queue")();
while (true)
{
shm::shared_string v(char_alloc);
if (queue->pop(v))
std::cout << "Processed: '" << v << "'\n";
}
}
all:consumer producer
CPPFLAGS+=-std=c++03 -Wall -pedantic
CPPFLAGS+=-g -O0
CPPFLAGS+=-isystem ~/custom/boost/
LDFLAGS+=-L ~/custom/boost/stage/lib/ -Wl,-rpath,/home/sehe/custom/boost/stage/lib
LDFLAGS+=-lboost_system -lrt -lpthread
%:%.cpp
$(CXX) $(CPPFLAGS) $^ -o $@ $(LDFLAGS)
#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>
int main()
{
// create segment and corresponding allocator
bip::managed_shared_memory segment(bip::open_or_create, "MySharedMemory", 65536);
shm::char_alloc char_alloc(segment.get_segment_manager());
// Ringbuffer fully constructed in shared memory. The element strings are
// also allocated from the same shared memory segment. This vector can be
// safely accessed from other processes.
shm::ring_buffer *queue = segment.find_or_construct<shm::ring_buffer>("queue")();
const char* messages[] = { "hello world", "the answer is 42", "where is your towel", 0 };
for (const char** msg_it = messages; *msg_it; ++msg_it)
{
sleep(1);
queue->push(shm::shared_string(*msg_it, char_alloc));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment