Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

multiple threads with Vector iterator

I 've declared a vector as

typedef std::vector< unsigned int > SampleList;

and declared Samplist type member variable in a class.

I am accessing this vector from another class with multiple threads.

I am adding , deleting , Reading values values from different threads. I am reading this value frequently like the following.

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

}

The value for itrSample becomes junk value like 4261281277.

I tried to guard this list with critical secion. Still I got this issue. Can you suggest and solution. It will be very helpful to me.

like image 601
Prabhu Avatar asked Jul 06 '11 12:07

Prabhu


3 Answers

As soon as somebody adds or deletes a member of the vector, you iterator becomes invalid.

Especially if elements are added, the internal buffer might have to be reallocated. But also if objects are deleted, the end() is moving and you might miss it.

You must have a lock to protect the vector while iterating over it.

like image 132
Bo Persson Avatar answered Sep 21 '22 16:09

Bo Persson


Can you show us how you do your critical sections? Because Mutex can definitely solve your problem

Then, a bit of guessing, if you still have issues even with critical sections, this might happen because insertion and deletion invalidates iterators.

if you do :

  ...
  {
    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)
  } 

then, this cause concurrent errors. itrSample becomes invalid.

A solution would be :

  ...
  {
    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)
like image 28
B. Decoster Avatar answered Sep 20 '22 16:09

B. Decoster


4261281277 is 0xFDFDFDFD which seems like maybe an uninitialized memory area on your platform. I'd try running your program under valgrind (or some similar tool on Windows) to flush out your memory access errors.

like image 28
John Zwinck Avatar answered Sep 21 '22 16:09

John Zwinck