malkusch / lock
Mutex library for exclusive code execution.
Installs: 7 170 334
Dependents: 28
Suggesters: 1
Security: 0
Stars: 935
Watchers: 29
Forks: 88
Open Issues: 3
Requires
- php: >=7.4 <8.5
- psr/log: ^1.0 || ^2.0 || ^3.0
- symfony/polyfill-php80: ^1.28
Requires (Dev)
- ext-igbinary: *
- ext-lzf: *
- ext-memcached: *
- ext-pcntl: *
- ext-pdo: *
- ext-pdo_mysql: *
- ext-pdo_sqlite: *
- ext-redis: *
- ext-sysvsem: *
- eloquent/liberator: ^2.0 || ^3.0
- ergebnis/composer-normalize: ^2.13
- ergebnis/phpunit-slow-test-detector: ^2.9
- friendsofphp/php-cs-fixer: ^3.0
- mikey179/vfsstream: ^1.6.11
- php-mock/php-mock-phpunit: ^2.1
- phpstan/extension-installer: ^1.1
- phpstan/phpstan: ^2.0
- phpstan/phpstan-deprecation-rules: ^2.0
- phpstan/phpstan-strict-rules: ^2.0
- phpunit/phpunit: ^9.5.25 || ^10.0 || ^11.0
- predis/predis: ^1.1.8
- spatie/async: ^1.5
Suggests
- ext-igbinary: To use this library with PHP Redis igbinary serializer enabled.
- ext-lzf: To use this library with PHP Redis lzf compression enabled.
- ext-pcntl: Enables locking with flock without busy waiting in CLI scripts.
- ext-redis: To use this library with the PHP Redis extension.
- ext-sysvsem: Enables locking using semaphores.
- predis/predis: To use this library with predis.
This package is auto-updated.
Last update: 2024-12-17 01:42:19 UTC
README
Requirements | Installation | Usage | Implementations | Authors | License
php-lock/lock
This library helps executing critical code in concurrent situations in serialized fashion.
php-lock/lock follows semantic versioning.
Requirements
- PHP 7.4 - 8.4
- Optionally nrk/predis to use the Predis locks.
- Optionally the php-pcntl extension to enable locking with
flock()
without busy waiting in CLI scripts. - Optionally
flock()
,ext-redis
,ext-pdo_mysql
,ext-pdo_sqlite
,ext-pdo_pgsql
orext-memcached
can be used as a backend for locks. See examples below. - If
ext-redis
is used for locking and is configured to use igbinary for serialization or lzf for compression, additionallyext-igbinary
and/orext-lzf
have to be installed.
Installation
Composer
To use this library through composer, run the following terminal command inside your repository's root folder.
composer require malkusch/lock
Usage
This library uses the namespace Malkusch\Lock
.
Mutex
The Malkusch\Lock\Mutex\Mutex
interface provides the base API for this library.
Mutex::synchronized()
Malkusch\Lock\Mutex\Mutex::synchronized()
executes code exclusively. This
method guarantees that the code is only executed by one process at once. Other
processes have to wait until the mutex is available. The critical code may throw
an exception, which would release the lock as well.
This method returns whatever is returned to the given callable. The return
value is not checked, thus it is up to the user to decide if for example the
return value false
or null
should be seen as a failed action.
Example:
$newBalance = $mutex->synchronized(static function () use ($bankAccount, $amount) { $balance = $bankAccount->getBalance(); $balance -= $amount; if ($balance < 0) { throw new \DomainException('You have no credit'); } $bankAccount->setBalance($balance); return $balance; });
Mutex::check()
Malkusch\Lock\Mutex\Mutex::check()
sets a callable, which will be
executed when Malkusch\Lock\Util\DoubleCheckedLocking::then()
is called,
and performs a double-checked locking pattern, where it's return value decides
if the lock needs to be acquired and the synchronized code to be executed.
See https://en.wikipedia.org/wiki/Double-checked_locking for a more detailed explanation of that feature.
If the check's callable returns false
, no lock will be acquired and the
synchronized code will not be executed. In this case the
Malkusch\Lock\Util\DoubleCheckedLocking::then()
method, will also return
false
to indicate that the check did not pass either before or after acquiring
the lock.
In the case where the check's callable returns a value other than false
, the
Malkusch\Lock\Util\DoubleCheckedLocking::then()
method, will
try to acquire the lock and on success will perform the check again. Only when
the check returns something other than false
a second time, the synchronized
code callable, which has been passed to then()
will be executed. In this case
the return value of then()
will be what ever the given callable returns and
thus up to the user to return false
or null
to indicate a failed action as
this return value will not be checked by the library.
Example:
$newBalance = $mutex->check(static function () use ($bankAccount, $amount): bool { return $bankAccount->getBalance() >= $amount; })->then(static function () use ($bankAccount, $amount) { $balance = $bankAccount->getBalance(); $balance -= $amount; $bankAccount->setBalance($balance); return $balance; });
LockReleaseException::getCode{Exception, Result}()
Mutex implementations based on Malkush\Lock\Mutex\AbstractLockMutex
will throw
Malkusch\Lock\Exception\LockReleaseException
in case of lock release
problem, but the synchronized code block will be already executed at this point.
In order to read the code result (or an exception thrown there),
LockReleaseException
provides methods to extract it.
Example:
try { $result = $mutex->synchronized(static function () { if (someCondition()) { throw new \DomainException(); } return 'result'; }); } catch (LockReleaseException $e) { if ($e->getCodeException() !== null) { // do something with the $e->getCodeException() exception } else { // do something with the $e->getCodeResult() result } throw $e; }
Implementations
You can choose from one of the provided Malkusch\Lock\Mutex\Mutex
interface
implementations or create/extend your own implementation.
FlockMutex
The FlockMutex is a lock implementation based on
flock()
.
Example:
$mutex = new FlockMutex(fopen(__FILE__, 'r'));
Timeouts are supported as an optional second argument. This uses the ext-pcntl
extension if possible or busy waiting if not.
MemcachedMutex
The MemcachedMutex is a spinlock implementation which uses the
Memcached
extension.
Example:
$memcached = new \Memcached(); $memcached->addServer('localhost', 11211); $mutex = new MemcachedMutex('balance', $memcached);
RedisMutex
The RedisMutex is a lock implementation which supports the
phpredis
extension
or Predis
API clients.
Both Redis and Valkey servers are supported.
If used with a cluster of Redis servers, acquiring and releasing locks will continue to function as long as a majority of the servers still works.
Example:
$redis = new \Redis(); $redis->connect('localhost'); // OR $redis = new \Predis\Client('redis://localhost'); $mutex = new RedisMutex($redis, 'balance');
SemaphoreMutex
The SemaphoreMutex is a lock implementation based on Semaphore.
Example:
$semaphore = sem_get(ftok(__FILE__, 'a')); $mutex = new SemaphoreMutex($semaphore);
MySQLMutex
The MySQLMutex uses MySQL's
GET_LOCK
function.
Both MySQL and MariaDB servers are supported.
It supports timeouts. If the connection to the database server is lost or interrupted, the lock is automatically released.
Note that before MySQL 5.7.5 you cannot use nested locks, any new lock will silently release already held locks. You should probably refrain from using this mutex on MySQL versions < 5.7.5.
Also note that GET_LOCK
function is server wide and the MySQL manual suggests
you to namespace your locks like dbname.lockname
.
$pdo = new \PDO('mysql:host=localhost;dbname=test', 'username'); $mutex = new MySQLMutex($pdo, 'balance', 15);
PostgreSQLMutex
The PostgreSQLMutex uses PostgreSQL's advisory locking functions.
Named locks are offered. PostgreSQL locking functions require integers but the conversion is handled automatically.
No timeouts are supported. If the connection to the database server is lost or interrupted, the lock is automatically released.
$pdo = new \PDO('pgsql:host=localhost;dbname=test', 'username'); $mutex = new PostgreSQLMutex($pdo, 'balance');
DistributedMutex
The DistributedMutex is the distributed lock implementation of
RedLock which supports
one or more Malkush\Lock\Mutex\AbstractSpinlockMutex
instances.
Example:
$mutex = new DistributedMutex([ new \Predis\Client('redis://10.0.0.1'), new \Predis\Client('redis://10.0.0.2'), ], 'balance');
Authors
Since year 2015 the development was led by Markus Malkusch, Willem Stuursma-Ruwen and many GitHub contributors.
Currently this library is maintained by Michael Voříšek - GitHub | LinkedIn.
Commercial support is available.
License
This project is free and is licensed under the MIT.