2010-12-06 55 views
0

我创建了一个共享内存,其中包含一个列表。我需要连续添加节点到列表中。 我的另一个应用程序读取列表并弹出读取的内容。 我面临的问题是弹出的节点不释放内存,所以当第一个应用程序不断插入点时,它会引发分段错误。请指导我如何释放节点,以便我的第一个应用程序可以使用该空间分配新节点。使用boost库释放共享内存中的节点内存

的片段我的代码是

#include </tcs/dev/lib/boost_1_38_0/boost/interprocess/managed_shared_memory.hpp> 
#include </tcs/dev/lib/boost_1_38_0/boost/interprocess/containers/list.hpp> 
#include </tcs/dev/lib/boost_1_38_0/boost/interprocess/allocators/allocator.hpp> 
#include </tcs/dev/lib/boost_1_38_0/boost/multi_index_container.hpp> 

#include <algorithm> 
#include<iostream> 
using namespace std; 
using namespace boost; 
using namespace multi_index; 

class marketdata 
{ 
    public: 
    int x; 
    float y; 
}; 


int main() 
{ 
    marketdata m[0]; 
    m[0].x=1; 
    m[0].y=1; 
    // boost::interprocess::list iterator itr; 

    using namespace boost::interprocess; 
    try{ 
     managed_shared_memory segment 
     (open_only 
     ,"MySharedMemory"); //segment name 
     typedef boost::interprocess::allocator<marketdata, managed_shared_memory::segment_manager> 
     ShmemAllocator; 
     typedef boost::interprocess::list<marketdata, ShmemAllocator> MyList; 
     MyList *mylist = segment.find<MyList>("MyList").first; 
boost::interprocess::list<marketdata, ShmemAllocator> :: iterator itr; 
      for(itr=mylist->begin(); itr != mylist->end(); ++itr) 
       { cout << (*itr).x << " "; 
       cout << endl; 
       mylist->pop_front(); 
       //multi_index::multi_index_container::delete_node_(itr); 
       sleep(1); 
       } 

     segment.destroy<MyList>("MyList"); 
    } 
    catch(...){ 
     shared_memory_object::remove("MySharedMemory"); 
     throw; 
    } 
    shared_memory_object::remove("MySharedMemory"); 
    return 0; 
} 
+0

为什么你的绝对路径包括?这将使升级到更高版本真的很烂! – 2010-12-06 06:25:21

+0

感谢比利你的建议。这只是为了一些测试目的,所以增加了绝对路径。肯定会改变这个 – user531805 2010-12-06 06:42:26

回答

0

你可能需要一个互斥锁。您不能只在线程/进程间应用程序中添加和删除内存,同时考虑到一个线程/进程可能正在尝试访问内存,而另一个线程正在使用它。