public void WeakCompareAndSet() { AtomicReference <T> ai = new AtomicReference <T>(one); while (!ai.WeakCompareAndSet(one, two)) { } while (!ai.WeakCompareAndSet(two, m4)) { } Assert.AreEqual(m4, ai.Value); while (!ai.WeakCompareAndSet(m4, seven)) { } Assert.AreEqual(seven, ai.Value); Assert.IsFalse(ai.WeakCompareAndSet(m4, seven)); }
/// <summary> /// Atomically sets the value of both the reference and stamp /// to the given update values if the /// current reference is equals to the expected reference /// and the current stamp is equal to the expected stamp. Any given /// invocation of this operation may fail (return /// false) spuriously, but repeated invocation when /// the current value holds the expected value and no other thread /// is also attempting to set the value will eventually succeed. /// </summary> /// <param name="expectedReference"> /// The expected value of the reference /// </param> /// <param name="newReference"> /// The new value for the reference /// </param> /// <param name="expectedStamp"> /// The expected value of the stamp /// </param> /// <param name="newStamp"> /// The new value for the stamp /// </param> /// <returns> /// True if successful /// </returns> public virtual bool WeakCompareAndSet(T expectedReference, T newReference, int expectedStamp, int newStamp) { ReferenceIntegerPair <T> current = Pair; return(expectedReference.Equals(current.Reference) && expectedStamp == current.Integer && ((newReference.Equals(current.Reference) && newStamp == current.Integer) || _atomicReference.WeakCompareAndSet(current, new ReferenceIntegerPair <T>(newReference, newStamp)))); }
/// <summary> /// Atomically sets both the value and stamp to the given update values /// if the current value and the expected value <see cref="AreEqual"/> /// and the current stamp is equal to the expected stamp. Any given /// invocation of this operation may fail (return /// false) spuriously, but repeated invocation when /// the current value holds the expected value and no other thread /// is also attempting to set the value will eventually succeed. /// </summary> /// <param name="expectedValue"> /// The expected value /// </param> /// <param name="newValue"> /// The new value /// </param> /// <param name="expectedStamp"> /// The expected value of the stamp /// </param> /// <param name="newStamp"> /// The new value for the stamp /// </param> /// <returns> /// True if successful /// </returns> public virtual bool WeakCompareAndSet(T expectedValue, T newValue, int expectedStamp, int newStamp) { ValueIntegerPair current = Pair; return(AreEqual(expectedValue, current.Value) && expectedStamp == current.Integer && ((AreEqual(newValue, current.Value) && newStamp == current.Integer) || _atomicReference.WeakCompareAndSet(current, new ValueIntegerPair(newValue, newStamp)))); }