PHP Class malkusch\lock\mutex\CASMutex

This mutex doesn't lock at all. It implements the compare-and-swap approach. I.e. it will repeat executing the code block until it wasn't modified in between. Use this only when you know that concurrency is a rare event.
Author: Markus Malkusch ([email protected])
Inheritance: extends Mutex
Datei anzeigen Open project: malkusch/lock Class Usage Examples

Public Methods

Method Description
__construct ( integer $timeout = 3 ) Sets the timeout.
notify ( ) Notifies the Mutex about a successfull CAS operation.
synchronized ( callable $code ) : mixed Repeats executing a code until a compare-and-swap operation was succesful.

Method Details

__construct() public method

The default is 3 seconds.
public __construct ( integer $timeout = 3 )
$timeout integer The timeout in seconds.

notify() public method

Notifies the Mutex about a successfull CAS operation.
public notify ( )

synchronized() public method

The code has to be designed in a way that it can be repeated without any side effects. When the CAS operation was successful it should notify this mutex by calling {@link CASMutex::notify()}. I.e. the only side effects of the code may happen after a successful CAS operation. The CAS operation itself is a valid side effect as well. If the code throws an exception it will stop repeating the execution. Example: $mutex = new CASMutex(); $mutex->synchronized(function () use ($memcached, $mutex, $amount) { $balance = $memcached->get("balance", null, $casToken); $balance -= $amount; if (!$memcached->cas($casToken, "balance", $balance)) { return; } $mutex->notify(); });
public synchronized ( callable $code ) : mixed
$code callable The synchronized execution block.
return mixed The return value of the execution block.