스레드 안전 참조 카운터를 구현하는 방법에 대해 많은 질문이 있습니다. 그리고 가장 많이 투표 된 대답은 "원자 증가/감소 사용"입니다. 좋아요, 이것은 refCounter whitout을 읽고 쓰는 다른 방법을 쓰는 좋은 방법입니다. 그러나.스레드 안전 참조 카운팅에 대한 또 다른 질문
내 코드는 다음과 같습니다
void String::Release()
{
if (0 == AtomicDecrement(&refCounter)))
delete buffer;
}
겠어요 - 나는 refCounter를 줄이고 안전하게 읽습니다. 하지만 다른 스레드가 내 refCounter를 0으로 비교하는 동안 증가 시키면 어떻게 될까요 ????
내가 틀렸어?
편집 : (예)
String* globalString = new String(); // refCount == 1 after that.
// thread 0:
delete globalString;
// This invokes String::Release().
// After AtomicDecrement() counter becomes zero.
// Exactly after atomic decrement current thread switches to thread 1.
// thread 1:
String myCopy = *globalString;
// This invokes AddRef();
// globalString is alive;
// internal buffer is still not deleted but refCounter is zero;
// We increment and switch back to thread 0 where buffer will be
// succefully deleted;
은 내가 잘못 건가요?
? 값 0은 문자 그대로 "no reference left"를 의미합니다. –