다른 스레드에서 두 가지 방법으로 작동해야하는 컨테이너 (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
이 추가 또는 제거 작업에서 '보호'되었는지 확인하기 위해 사용할 수있는 데이터 구조는 무엇입니까?
+1. Boost에는 다음과 같은 구현이 있습니다. http://www.boost.org/doc/libs/1_46_1/doc/html/thread/synchronization.html#thread.synchronization.mutex_types.shared_mutex –
@Evan, @larsmans 꽤 이해할 것입니다. 어디에 넣을까요? 전역으로 정의하고 C :: Iterate ...와 A 메소드를 넣으시겠습니까? 읽기 또는 쓰기가 수행되는지 여부를 어떻게 알 수 있습니까? –
@Matt : 목록 자체와 동일한 범위/소유권을 가져야합니다. 목록이 전역이면 잠금은 전역이어야합니다. 어떤 객체가 목록을 소유하고 있다면, 그 같은 객체는 자물쇠를 소유해야한다. –