Q:

Implement atomic counter in Memcached without cas

We have a web page want to limit uo to 100 people can access concurrently, so we use a memcached to implement a global counter, e.g.
We are using http://www.php.net/manual/en/class.memcache.php so there is not cas, current code is something like
$count = $memcache_obj->get('count');
if ($count < 100) {
   $memcache_obj->set('count', $count+1);
   echo "Welcome";
} else {
   echo "No luck";
}

As you can see there is race condition in the above code and but if we are not going to replace memcached extension which support cas, it is able to support it using PHP code only?

A:

As answer to "emcconville". This is non-blocking even without CAS.
If your concerned about race conditions, and the count value is completely arbitrary, you can use Memcache::increment directly before any business logic.
The increment method will return the current value after the incrementation takes place; of which, you can compare results. Increment will also return false if the key has yet to be set; allowing for your application to deal with it as needed. 
$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');

}

A:

If your concerned about race conditions, and the count value is completely arbitrary, you can use Memcache::increment directly before any business logic.
The increment method will return the current value after the incrementation takes place; of which, you can compare results. Increment will also return false if the key has yet to be set; allowing for your application to deal with it as needed. 
$current = $memcache_obj->increment('count');

if($current === false) {

  // NOT_FOUND, so let's create it
  $memcache_obj->set('count',1); // <-- still risk of race-condition
  echo "Your the first!";

} else if ($current < 100) {

  echo "Hazah! Your under the limit.";

} else {

  echo "Ah Snap! No Luck";
  // If your worried about the value growing _too_ big, just drop the value down.
  // $memcache_obj->decrement('count');

}

