Search code examples
phpapc

What is the real usage of apc_cas() function?


I wonder what a real life example that I need to use the apc_cas function in PHP.


Solution

  • A simple example is a counter. Assume we have a key counter and a function which increases the counter (note that this would be better suited for the apc_inc function but let's play along):

    function incCounter(){
        //Get the current value increment and set
        $c = apc_fetch('counter');
        $c++;
        apc_store('counter',$c);
    }
    

    However the above has an issue. If two requests occur at the same time both will get the same value of $c and increment it meaning the counter will only be incremented by one.

    Using apc_cas however let's you guarantee that the value you are updating is the old one and that it hasn't been changed in the meantime.