Existen innumerables preguntas sobre cómo implementar contadores de referencia seguros para subprocesos. Y una respuesta común altamente votada es: "usar incrementos/decrementos atómicos". Ok, esta es una buena forma de leer y escribir refCounter sin otro hilo que lo cambie entre medio. Pero.Otra pregunta sobre el conteo seguro de subprocesos
Mi código es:
void String::Release()
{
if (0 == AtomicDecrement(&refCounter)))
delete buffer;
}
So. Decremento y leo refCounter en caja fuerte. Pero ¿y si otro hilo INCREMENTARA mi refCounter mientras lo comparo con cero?
¿Estoy equivocado?
EDIT: (ejemplo)
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;
¿Me equivoco?
¿Cómo puede otro hilo incrementar el contador si no tiene una referencia al objeto ? Un valor de 0 significa literalmente "no quedan referencias". –