2013-04-27 26 views
1

以原子方式執行此操作有可能嗎?PHP APC以原子方式獲取並設置值

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

「mykey」在其他進程中頻繁增加,我不想錯過它們。

+1

目前尚不清楚你想完成什麼。它看起來像你總是想把它設置爲零。如果是這樣,爲什麼要存儲它? – Rob 2013-04-27 18:32:40

回答

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()

內存緩存具有cas(),也可用於非整數值。

+1

你的答案有誤導性。 apc_cas不適用於除整數之外的任何內容。 – Stephen 2014-01-06 22:34:57

+0

閱讀文檔後,您完全正確。我正在考慮memcache的'cas()'函數,儘管函數簽名有點不同,但它對任何值都有好處。修復帖子... – slashingweapon 2014-01-07 19:20:14

+0

反投票:-) – Stephen 2014-01-08 11:07:12