最近在写一个多线程的应用时用到了STL率的vector容器。程序有A,B两个线程。A线程主要是对vector进行写入,B线程主要是对Vector中的数据进行轮询并作一些删除操作
vector中使用的数据结构如下typedef struct tagMyDInfo
{
    char name[100];
                int id;
                char address[500];
}tMyDInfo,*ptMyDInfovector<tMyDInfo> g_vtInfo;A Thread核心代码如下:
vector<tMyDInfo>::iterator pos;
vector<tMyDInfo>::iterator begin;begin = g_vtInfo.begin();
pos = begin;for( being; pos != g_vtInfo.end();)
{
     if( 0 == strcmp(pos->name,"jay") )
     {
        EnterCriticalSection(&g_csdate);
         pos = g_vtInfo.erase(pos);///这里有时候pos无效。
     LeaveCriticalSection(&g_csdate);
     
      }
      else
      {
             ++pos ;
      }
}B Thread核心代码如下:    tMyDInfo mydate 
while (true)
{
      getmydate(&mydate);
       EnterCriticalSection(&g_csdate);
  g_vtInfo.push_back(mydate);
      LeaveCriticalSection(&g_csdate);}
问题:在A线程中有时候出现程序崩溃。
可能原因:由于B线程不停的写数据,导致g_vtInfo的内存不断扩大,STL对容器内存可能是到一定大小全部移到别一个位置。所以就出现pos指向vector的原内存无效。
解决方法:增加新地临界区在push_back的时候不能查找vector新代码如下:CRITICAL_SECTION g_cspushorerase;
A Thread核心代码如下:
vector<tMyDInfo>::iterator pos;
vector<tMyDInfo>::iterator begin;begin = g_vtInfo.begin();
pos = begin;EnterCriticalSection(&g_cspushorerase);
for( being; pos != g_vtInfo.end();)
{
     if( 0 == strcmp(pos->name,"jay") )
     {
        EnterCriticalSection(&g_csdate);
         pos = g_vtInfo.erase(pos);//这里有时候pos无效。
     LeaveCriticalSection(&g_csdate);
     
      }
      else
      {
             ++pos ;
      }
}
LeaveCriticalSection(&g_cspushorerase);B Thread核心代码如下:    tMyDInfo mydate 
while (true)
{
      getmydate(&mydate);
       EnterCriticalSection(&g_cspushorerase);
       EnterCriticalSection(&g_csdate);
  g_vtInfo.push_back(mydate);
      LeaveCriticalSection(&g_csdate);
      LeaveCriticalSection(&g_cspushorerase);
}
我的问题暂时这样解决,如果大家有不同意见的话欢迎留言。如有错误请指不出胜感激! 程序运行几天后,我发现我加的临界区只能减少程序崩溃的次数,不知道那个知道是什么原因?1.vector在push_back时如果原来空间不够是怎么处理的?,2.会不会把所有数据移到另一个地方?3.如果会的话pos是不是也自动正确指向,如果不是怎么处理?谢谢问题有点多哈

解决方案 »

  1.   

    曾经用过vector,感觉没出什么问题。看看MSDN哦  An iterator that designates the first element remaining beyond any elements removed, or a pointer to the end of the vector if no such element exists.删除一个数,返回下一个位置,当你删除最后一个位置的时候返回的仍然是最后一个位置,所以无效吧。
      

  2.   

    楼主太不厚道了啊~分这么少啊~哈哈Memory will be reallocated automatically if more than capacity() - size() elements are inserted into the vector.A vector's iterators are invalidated when its memory is reallocated. inserting or deleting an element in the middle of a vector invalidates all iterators that point to elements following the insertion or deletion point. It follows that you can prevent a vector's iterators from being invalidated if you use reserve() to preallocate as much memory as the vector will ever use, and if all insertions and deletions are at the vector's end.如果觉得麻烦可以试试list.
      

  3.   

    感谢daidongsheng,不知道怎么回事,我CSDN上的分没有了,不知道在那查得到,我付20分都不行。