Get/cas operation on a not found item
Hi,
I've a question about the "get" operation with cas token.
How can I handle the situation of a get-cas (get with cas) on a not found item?
I thought to obtain a cas token also with item not found, and insert the item with locking (cas operation).
But I read that the cas token is returned *only* if the item is found, so how can I insert the item?
Es.
do
{
// get-cas item
$l_aFriendData = $g_Memcached->get($l_sFriendId, null, $cas);
if ($l_aFriendData == null)
{
// item not found
// create item value
$l_aFriendData = array();
// Is this section right?
//
// insert item
$g_Memcached->set($l_sFriendId, $l_aFriendData);
//
// get-cas again (now the item is inserted)
$l_aFriendData = $GLOBALS["memcache"]->get($l_sFriendId, null, $cas);
//
// modify item value
$l_aFriendData[...] = ...;
}
else
{
// item found
// modify item value
$l_aFriendData[...] = ...;
}
// set operation with cas
$g_Memcached->cas($cas, $l_sFriendId, $l_aFriendData);
} while ($GLOBALS["memcache"]->getResultCode() != Memcached::RES_SUCCESS);
Is the "$g_Memcached->set($l_sFriendId, $l_aFriendData);" right, in the "item not found" case? There is no locking!
If two users (A and B) try to access the same (not found) item:
- A get-cas on "item" -> not found
- B get-cas on "item" -> not found
- A insert (no-cas) "item"
- A set-cas on "item"
- B insert (no-cas) "item"
- B set-cas on "item"
We lose the operations of user A.
How can I insert a not found key with locking?
Thanks.
Usually you'll use the add() operation, which atomically adds an item only if it doesn't already exist.