+ // Found an item in the skiplist that matches the key.
+ uint64_t old_item_val = old_item->val;
+ do {
+ // If the item's value is DOES_NOT_EXIST it means another thread removed the node out from under us.
+ if (EXPECT_FALSE(old_item_val == DOES_NOT_EXIST)) {
+ TRACE("s2", "sl_cas: lost a race, found an item but another thread removed it. retry", 0, 0);
+ break; // retry
+ }
+
+ if (EXPECT_FALSE(expectation == EXPECT_DOES_NOT_EXIST)) {
+ TRACE("s1", "sl_cas: found an item %p in the skiplist that matched the key. the expectation was "
+ "not met, the skiplist was not changed", old_item, old_item_val);
+ return old_item_val; // failure
+ }
+
+ // Use a CAS and not a SWAP. If the node is in the process of being removed and we used a SWAP, we could
+ // replace DOES_NOT_EXIST with our value. Then another thread that is updating the value could think it
+ // succeeded and return our value even though we indicated that the node has been removed. If the CAS
+ // fails it means another thread either removed the node or updated its value.
+ uint64_t ret_val = SYNC_CAS(&old_item->val, old_item_val, new_val);
+ if (ret_val == old_item_val) {
+ TRACE("s1", "sl_cas: the CAS succeeded. updated the value of the item", 0, 0);
+ return ret_val; // success
+ }
+ TRACE("s2", "sl_cas: lost a race. the CAS failed. another thread changed the item's value", 0, 0);
+
+ old_item_val = ret_val;
+ } while (1);