我有一个容器(C ++),需要两种不同线程的操作:
1)添加和删除元素,
2)迭代其成员。
很明显,在进行迭代时删除元素会导致灾难性后果。 代码大致如下:
class A
{
public:
...
void AddItem(const T& item, int index) { /*Put item into my_stuff at index*/ }
void RemoveItem(const T& item) { /*Take item out of m_stuff*/ }
const list<T>& MyStuff() { return my_stuff; } //*Hate* this, but see class C
private:
Mutex mutex; //Goes in the *Item methods, but is largely worthless in MyStuff()
list<T> my_stuff; //Just as well a vector or deque
};
extern A a; //defined in the .cpp file
class B
{
...
void SomeFunction() { ... a.RemoveItem(item); }
};
class C
{
...
void IterateOverStuff()
{
const list<T>& my_stuff(a.MyStuff());
for (list<T>::const_iterator it=my_stuff.begin(); it!=my_stuff.end(); ++it)
{
...
}
}
};
再次提醒,B::SomeFunction()
和 C::IterateOverStuff()
是异步调用的。有什么数据结构可以使用以确保在迭代期间my_stuff
受到添加或删除操作的“保护”?