![]() |
#2
yuccn2013-11-12 13:37
|

#include <boost/interprocess/managed_shared_memory.hpp>
#include <boost/interprocess/allocators/allocator.hpp>
#include <boost/interprocess/containers/vector.hpp>
#include <boost/interprocess/sync/named_mutex.hpp>
#include <iostream>
#define SHM_SIZE 2*1024*1024
typedef boost::interprocess::allocator<int,boost::interprocess::managed_shared_memory::segment_manager> ShmemAllocator;
typedef boost::interprocess::vector<int,ShmemAllocator> MyVector;
class CShm
{
public:
CShm();
~CShm();
void Task(void);
private:
boost::interprocess::named_mutex mutex;
MyVector *pObj;
};
CShm::CShm():mutex(boost::interprocess::open_or_create,"shm_mtx")
{
try
{
boost::interprocess::managed_shared_memory segment(boost::interprocess::open_or_create,"SHM",SHM_SIZE);
const ShmemAllocator alloc_inst(segment.get_segment_manager());
MyVector *pObj = segment.construct<MyVector>("MyVector")(alloc_inst);
}
catch (boost::interprocess::interprocess_exception& ex)
{
std::cout<<ex.what()<<std::endl;
}
}
CShm::~CShm()
{
mutex.remove("shm_mtx");
boost::interprocess::shared_memory_object::remove("SHM");
}
void CShm::Task(void)
{
for (int i = 0;i < 10; i++)
{
mutex.lock();
pObj->push_back(i+1);
mutex.unlock();
}
mutex.lock();
for (MyVector::const_iterator it = pObj->begin(); it != pObj->end(); it++)
std::cout<<*it<<" ";
mutex.unlock();
}
int main()
{
CShm _gShm;
_gShm.Task();
return 0;
}
#include <boost/interprocess/allocators/allocator.hpp>
#include <boost/interprocess/containers/vector.hpp>
#include <boost/interprocess/sync/named_mutex.hpp>
#include <iostream>
#define SHM_SIZE 2*1024*1024
typedef boost::interprocess::allocator<int,boost::interprocess::managed_shared_memory::segment_manager> ShmemAllocator;
typedef boost::interprocess::vector<int,ShmemAllocator> MyVector;
class CShm
{
public:
CShm();
~CShm();
void Task(void);
private:
boost::interprocess::named_mutex mutex;
MyVector *pObj;
};
CShm::CShm():mutex(boost::interprocess::open_or_create,"shm_mtx")
{
try
{
boost::interprocess::managed_shared_memory segment(boost::interprocess::open_or_create,"SHM",SHM_SIZE);
const ShmemAllocator alloc_inst(segment.get_segment_manager());
MyVector *pObj = segment.construct<MyVector>("MyVector")(alloc_inst);
}
catch (boost::interprocess::interprocess_exception& ex)
{
std::cout<<ex.what()<<std::endl;
}
}
CShm::~CShm()
{
mutex.remove("shm_mtx");
boost::interprocess::shared_memory_object::remove("SHM");
}
void CShm::Task(void)
{
for (int i = 0;i < 10; i++)
{
mutex.lock();
pObj->push_back(i+1);
mutex.unlock();
}
mutex.lock();
for (MyVector::const_iterator it = pObj->begin(); it != pObj->end(); it++)
std::cout<<*it<<" ";
mutex.unlock();
}
int main()
{
CShm _gShm;
_gShm.Task();
return 0;
}