【问题标题】:multiple threads with Vector iterator带有向量迭代器的多线程
【发布时间】:2011-07-06 20:42:51
【问题描述】:

我已将向量声明为

typedef std::vector SampleList;

并在类中声明了 Samplist 类型的成员变量。

我正在从另一个具有多个线程的类访问此向量。

我正在添加、删除、读取来自不同线程的值。我经常像下面这样读取这个值。

SampleList* listSample;
listSample= ptr->GetList();
while(true)
{   
    SampleList::iterator itrSample;
    itrSample = listSample->begin();

    unsigned int nId = 0;


    for ( ; itrSample < listRoundRobinSensor->end(); ++itrSample )
    {           
         nId =(unsigned int) *itrSample ;
    }

}

itrSample 的值变成像 4261281277 这样的垃圾值。

我试图用critical secion 保护这个列表。我仍然遇到了这个问题。您能否提出建议和解决方案。这对我很有帮助。

【问题讨论】:

    标签: c++ multithreading stdvector


    【解决方案1】:

    一旦有人添加或删除向量的成员,您的迭代器就会失效。

    特别是如果添加元素,内部缓冲区可能必须重新分配。但如果对象被删除,end() 会移动,您可能会错过它。

    在迭代向量时,您必须有一个锁来保护它。

    【讨论】:

      【解决方案2】:

      您能告诉我们您是如何处理关键部分的吗?因为Mutex绝对可以解决你的问题

      然后,稍微猜测一下,如果您在关键部分仍然存在问题,这可能是因为插入和删除会使迭代器无效。

      如果你这样做:

        ...
        {
          for ( ; itrSample < listRoundRobinSensor->end(); ++itrSample )
          {        
            MutexLocker m(mutex);   
            nId =(unsigned int) *itrSample ;
            // Do horrible stuff like insertion/deletion
          } // m dies at the end of the scope (cf RAII)
        } 
      

      那么,这会导致并发错误。 itrSample 失效。

      解决方案是:

        ...
        {
          MutexLocker m(mutex);   
          for ( ; itrSample < listRoundRobinSensor->end(); ++itrSample )
          {   
            nId =(unsigned int) *itrSample ;
            // Do horrible stuff like insertion/deletion
          } 
        } // m dies at the end of the scope (cf RAII)
      

      【讨论】:

      • EnterCriticalSection( m_gCriticalSample );\n
      【解决方案3】:

      4261281277 是 0xFDFDFDFD,这看起来可能是您平台上未初始化的内存区域。我会尝试在 valgrind(或 Windows 上的一些类似工具)下运行您的程序,以清除您的内存访问错误。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-06-10
        • 2012-05-29
        • 2017-08-29
        • 2011-11-15
        相关资源
        最近更新 更多