PHP APC以原子方式获取和设置值

时间:2013-04-27 18:27:48

标签: php apc

是否可以以原子方式执行此操作?

$myvalue = apc_get("mykey");
apc_store("mykey",0);
// log/deal with myvalue 

“mykey”经常在其他过程中增加,我不想错过统计它们。

1 个答案:

答案 0 :(得分:3)

您正在寻找的功能是apc_cas()。 'cas'代表'比较和交换'。它将在缓存中保存一个值,但前提是它自上次提取后没有更改。如果函数失败,您只需重新获取缓存的值并尝试再次保存。这样可以确保不会跳过任何更改。

假设您希望以原子方式递增计数器。该技术将是:

apc_add('counter', 0); // set counter to zero, only if it does not already exist.    
$oldVar = apc_fetch('counter'); // get current counter

// do whatever you need to do with the counter ...

// ... when you are ready to increment it you can do this
while ( apc_cas('counter', $oldVar, intval($oldVar)+1) === false ) {
    // huh.  Someone else must have updated the counter while we were busy.
    // Fetch the current value, then try to increment it again.
    $oldVar = apc_fetch('counter');
}

恰恰相反,APC为此提供了专门的增量和减量,apc_inc()apc_dec()

Memcache有cas(),也适用于非整数值。