作为对“emcconville”的回答。即使没有 CAS,这也是非阻塞的。
如果您关心竞态条件,并且计数值是完全任意的,您可以Memcache::increment
在任何业务逻辑之前直接使用。
增量方法将在增量发生后返回当前值;其中,您可以比较结果。如果 key 尚未设置,increment 也将返回false ;允许您的应用程序根据需要处理它。
$current = $memcache_obj->increment('count');
if($current === false) {
// NOT_FOUND, so let's create it
// Will return false if has just been created by someone else.
$memcache_obj->add('count',0); // <-- no risk of race-condition
// At this point 'count' key is created by us or someone else (other server/process).
// "increment" will update 0 or whatever it is at the moment by 1.
$current = $memcache_obj->increment('count')
echo "You are the $current!";
}
if ($current < 100) {
echo "Hazah! You are under the limit. Congrats!";
} else {
echo "Ah Snap! No Luck - you reached the limit.";
// If your worried about the value growing _too_ big, just drop the value down.
// $memcache_obj->decrement('count');
}