写入共享内存队列时的Segfault

时间:2013-11-06 19:29:49

标签: c++ boost shared-memory boost-interprocess

我使用boost托管共享内存在共享内存上创建了boost deque。我有一个进程(进程A)将数据推送到队列的后面,另一个进程(进程B)从队列的前面读取并弹出前端。

我的进程A可以将数据推送到队列中而不会出现任何问题。但是当我启动我的进程B时,它会在读取队列前端的时刻发生段错误。进程B可以正确读取队列大小,只有当我从队列中读取或弹出一个元素时它才会段错误。

进程A创建共享内存并构造队列对象。当我的进程B找到构造的对象时。

我的SharedMemQueue是,

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;
};

非常感谢任何帮助, 感谢

1 个答案:

答案 0 :(得分:1)

如果您可以读取队列的大小而不是其元素,那么该队列可能只是一个处理程序并将其元素存储在其他位置。 您确定boost::interprocess::deque < int > queue;使用共享内存来分配其元素吗?