Reputation: 167
I need to create a queue like structure inside my structure which I use as shared memory. How can I do this ? My compiler is Visual C++.
Upvotes: 0
Views: 1260
Reputation: 1549
Upvotes: 0
Reputation: 754
Using a complex C++ object within shared memory is not so simple I fear. You have to consider two things.
1)
You need to create the class instance in the shared memory area instead of on the stack. You can to this by using the placement new operator. Example:
#include <new> // for placement new operator
class X
{
// whatever
};
// suppose this points to some shared memory area
void *shared_mem = getSharedMem();
// this creates an instance of X at the start address of shared_mem
new(shared_mem) X;
// now you have a reference to an instance of X in the shared memory area
X& shared_x = *reinterpret_cast<X*>(shared_mem);
Note, however, that only one process should be responsible for constructing that object in shared memory. Also the other processes participating need a means to know whether the object is already correctly initialized and can be safely accessed. Access also requires some kind of inter-process locking (on Win32 a named mutex, for example)
2)
If your class type requires dynamic memory like it is the case with a queue data structure then the memory can't come from the heap as usual, because the heap is local to one process. If you'd like to use an STL queue container then you can implement your own STL allocator class that gets its memory not from the heap but from shared memory.
The allocator class used is part of the STL template declaration. For example std::deque<T, A> where A is the allocator type. By default the standard STL allocator is used that gets its memory from the heap.
Your custom shared-memory allocator would then need to know from what shared memory address exactly the memory can be allocated. The allocator support in most STL implementations doesn't play very well with per-instance data of allocators (as to my knowledge) so you'd probably need some global/static data in the allocator such that it can know where to get shared memory from.
All in all you might be better off to write a simple custom queue class that operates on shared memory like described in 1). You could make the queue class use statically sized memory for example it could hold space for exactly 100 objects in the queue and if you exceed this limit then the operation fails.
Upvotes: 3