|
Boost Users : |
Subject: [Boost-users] Problem with Interprocess Synchronization MUTEX
From: Daniel Veneros (dann.vd_at_[hidden])
Date: 2010-02-05 10:05:05
Hi,
I have a problem, I need to access a shared memory segment from several
process and all at the same time.
I was looking at boost::interprocess threads but I'm not sure how to
implement the mutex.
this is the code I have(working):
#include <boost/interprocess/managed_shared_memory.hpp>
#include <boost/interprocess/containers/vector.hpp>
#include <boost/interprocess/containers/string.hpp>
#include <boost/interprocess/containers/map.hpp>
#include <boost/interprocess/allocators/allocator.hpp>
#include <cstdlib>
#include <string>
#include <iostream>
#include <map>
#include <sstream>
using namespace boost::interprocess;
typedef managed_shared_memory::segment_manager SegmentManager;
typedef allocator<void, SegmentManager> VoidAllocator;
typedef allocator<char, SegmentManager> CharAllocator;
typedef basic_string<char, std::char_traits<char>, CharAllocator>
BasicString;
class Action
{
int id;
BasicString task;
public:
Action(int num, const char *name, const VoidAllocator &void_alloc)
:id(num), task(name,void_alloc)
{}
void setId(int num);
void setTask(BasicString newTask);
int getId();
};
int Action::getId() {
return id;
}
void Action::setId(int num) {
id = num;
}
void Action::setTask(BasicString newTask) {
task = newTask;
}
typedef allocator<Action, SegmentManager> ActionAllocator;
typedef std::pair<const BasicString, Action> MapValueType;
typedef std::pair<BasicString, Action> MovableToMapValueType;
typedef allocator<MapValueType, SegmentManager> MapValueTypeAllocator;
typedef map<BasicString, Action, std::less<BasicString>,
MapValueTypeAllocator> MyMap;
void CreateAndFill() {
managed_shared_memory segment(create_only, "MySharedMemory", 65536);
VoidAllocator alloc_inst(segment.get_segment_manager());
MyMap *myMap = segment.construct<MyMap>("Map"
)(std::less<BasicString>(),alloc_inst);
std::string keyword;
std::string helper;
int i=0;
for(int adder = 0; adder<=1000; adder++)
{
keyword = "Hello";
std::stringstream out;
out << adder;
helper = out.str();
keyword = keyword + helper;//Creates a string "Hello" + adder
BasicString key(keyword.c_str(), alloc_inst);//string to BasicString
Action action(i,"ActionContent", alloc_inst);//puts values of Action
object
MapValueType value(key, action);
myMap->insert(value);
i++;
}
}
int main(int argc, char** argv) {
//Remove shared memory on construction and destruction
struct shm_remove {
shm_remove() {shared_memory_object::remove("MySharedMemory"); }
~shm_remove() {shared_memory_object::remove("MySharedMemory"); }
}remover;
CreateAndFill();
}
How and where do I have to set the mutex?? Is this anonymous or named?
Thanks!
Dann
Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net