[英]Segfault on writing to a Shared Memory Queue
我使用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;
};
任何幫助都非常感謝,謝謝
如果您可以讀取隊列的大小但不能讀取其元素,則該隊列可能只是一個處理程序,並將其元素存儲在其他位置。 您確定boost::interprocess::deque < int > queue;
使用您的共享內存來分配其元素?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.