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;
开发者_如何学Python 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.
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.
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)
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.
精彩评论