I created boost deque on a shared memory using boost managed shared memory. I have one process ( process A ) that pushes data to the back of the queue and another process (process B )that reads from the front of the queue and pops the front.
My process A can push data into the queue without any issues. But when I start my process B, it segfaults the moment it reads the front of the queue. process B can read the queue size correctly, it segfaults only when I read or pop an element from the queue.
Process A creates the shared memory and constructs the queue object. While my process B finds the constructed object.
My SharedMemQueue is,
struct QueueType
{
boost::interprocess::interprocess_mutex mutex;
boost::interprocess::interprocess_condition signal;
boost::interprocess::deque < int > queue;
};
class ShmQueue
{
public:
ShmQueue ( std::string name )
: _shm_name ( name )
{
}
~ShmQueue ( )
{
Deinit();
}
bool Init ( bool value = false )
{
bool result ( false );
try
{
if ( value )
{
shared_memory_object::remove ( _shm_name.c_str() );
_shm_mem = managed_shared_memory ( create_only, _shm_name.c_str(), 65356 );
_queue = _shm_mem.construct < QueueType > ( "Queue" )();
}
else
{
_shm_mem = managed_shared_memory ( open_only, _shm_name.c_str() );
_queue = _shm_mem.find < QueueType > ( "Queue" ).first;
}
}
catch ( interprocess_exception &e )
{
std::cout << e.what() << std::endl;
_queue = NULL;
}
if ( _queue != NULL )
{
result = true;
}
return result;
}
bool Deinit ( )
{
bool result ( false );
_shm_mem.destroy < QueueType > ( "Queue" );
shared_memory_object::remove ( _shm_name.c_str() );
return result;
}
void Push ( int value )
{
scoped_lock < interprocess_mutex > lock ( _queue->mutex );
if ( _queue->queue.size ( ) < 20 )
{
_queue->queue.push_back ( value );
}
}
int Pop ( )
{
int result ( -1 );
scoped_lock < interprocess_mutex > lock ( _queue->mutex );
if ( !_queue->queue.empty( ) )
{
result = _queue->queue.front();
_queue->queue.pop_front();
}
return result;
}
private:
std::string _shm_name;
QueueType * _queue;
managed_shared_memory _shm_mem;
};
Any help is much appreciated, Thanks