使用 Vector 迭代器的多线程
我已将向量声明为
typedef std::向量<无符号整数>样本列表;
并在类中声明了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。
我试图用关键部分
来保护这个列表。我仍然遇到这个问题。您能提出建议和解决方案吗?这对我很有帮助。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
一旦有人添加或删除向量的成员,你的迭代器就会变得无效。
特别是如果添加元素,可能必须重新分配内部缓冲区。但如果对象被删除,end() 也会移动,您可能会错过它。
您必须有一个锁来在迭代向量时保护它。
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.
您能向我们展示您如何处理关键部分吗?因为 Mutex 绝对可以解决你的问题
然后,猜测一下,如果即使关键部分仍然存在问题,这可能是因为插入和删除使迭代器无效而发生的。
如果你这样做:
那么,这会导致并发错误。
itrSample
变得无效。解决方案是:
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 :
then, this cause concurrent errors.
itrSample
becomes invalid.A solution would be :
4261281277 是 0xFDFDFDFD,这看起来可能是您平台上未初始化的内存区域。我会尝试在 valgrind (或 Windows 上的一些类似工具)下运行你的程序来清除你的内存访问错误。
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.