Search code examples
phpapc

How to ensure some statements are executed atomically without using locks?


My doubt: if there is a way by which we can ensure that a series of statements are executed in an atomic way. But one thing is sure that we don't need to use locks. So, is there any elegant way of doing it. For example I need to do the same in php. For Example: Statements to be executed:

  1. Fetch a key from APC cache.
  2. Do some operation on that.. let us say increment it.
  3. Save that to the Cache again.

I need it to do these things atomic because at a time many processes can update the same thing.

Thanks, Varun


Solution

  • Locks, Mutexes, Semaphores have all been invented for guaranteeing atomicity in multitasking/parallel computers.

    There are ways to optimize locking: the worst you can do is busy-waiting in a loop for a resource to be ready; while better solutions involve signaling/queuing to acquire a resource.

    It should be clear at this point that there's not a lot you can do to achieve atomicity without locking, expecially when there are more than one instruction in execution in a moment in time, even in a single CPU core (it's called pipelining).

    That said, this has been asked before here: APC caching and atomic operations