php - 在不使用 cas 的情况下在 Memcached 中实现原子计数器

标签 php algorithm transactions memcached

我们有一个网页想限制 uo 到 100 人可以同时访问,所以我们使用 memcached 来实现一个全局计数器,例如

我们正在使用 http://www.php.net/manual/en/class.memcache.php 所以没有 cas,当前代码是这样的

$count = $memcache_obj->get('count');
if ($count < 100) {
   $memcache_obj->set('count', $count+1);
   echo "Welcome";
} else {
   echo "No luck";
}

如您所见,上面的代码中存在竞争条件,但如果我们不打算替换支持 casmemcached 扩展,它能够支持它仅使用 PHP 代码?

最佳答案

作为对“emcconville”的回答。即使没有 CAS,这也是非阻塞的。

如果您担心竞争条件,并且计数值完全是任意的,您可以在任何业务逻辑之前直接使用 Memcache::increment

increment方法将在递增发生后返回当前值;其中,您可以比较结果。如果尚未设置 key ,增量也将返回 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');

}

关于php - 在不使用 cas 的情况下在 Memcached 中实现原子计数器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13132664/

相关文章:

c# - 写出最大素数

algorithm - 帮助大 O 表示法

jboss - 使用 javax.transaction.UserTransaction 在 EJB 中实现事务

php - MySQL从一个间隔中获取最小和最大范围

php - 为什么在 Wordpress 插件的类中使用 $this 会引发 fatal error ?

algorithm - 一个有趣的图形任务

database - 不可重复读和幻读有什么区别?

c# - Entity Framework 中的一个事务中的多个数据库

php - Woocommerce:在订单页面上显示产品变体描述

php - 强制链接不分两行