Let's say I have a boost interprocess vector in shared memory. One process may be iterating through it. If another process wants to concurrently clear the vector, what do I need to do so that I don't crash in the process that is doing the iteration?
PROCESS #1 - iterates over vector in shared memory
using namespace boost::interprocess;
typedef allocator<int, managed_shared_memory::segment_manager> ShmemAllocator;
typedef vector<int, ShmemAllocator> MyVector;
managed_shared_memory segment(create_only, "MySharedMemory", 65536);
const ShmemAllocator alloc_inst (segment.get_segment_manager());
MyVector *myvector = segment.construct<MyVector>("MyVector")(alloc_inst);
size_t size = myvector->size();
for (size_t i = 0; i < size; i++)
{
//potential crash when PROCESS 2 calls clear
int value = myvector->at(i);
}
PROCESS #2 - can potentially clear the vector in shared memory
using namespace boost::interprocess;
typedef allocator<int, managed_shared_memory::segment_manager> ShmemAllocator;
typedef vector<int, ShmemAllocator> MyVector;
managed_shared_memory segment(create_only, "MySharedMemory", 65536);
const ShmemAllocator alloc_inst (segment.get_segment_manager());
MyVector *myvector = segment.construct<MyVector>("MyVector")(alloc_inst);
if (somecondition)
myvector->clear();
Two things I was thinking: copy the vector to local memory std::vector before iterating. I'm not sure if the copy would be safe, though, either. Can't imagine it would
or
some sort of interprocess mutex, which for simplicity's sake, I'd like to avoid.