PHPackages                             malkusch/lock - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Database &amp; ORM](/categories/database)
4. /
5. malkusch/lock

ActiveLibrary[Database &amp; ORM](/categories/database)

malkusch/lock
=============

Mutex library for exclusive code execution.

3.1.1(2mo ago)9459.6M—6.9%92[2 issues](https://github.com/php-lock/lock/issues)[1 PRs](https://github.com/php-lock/lock/pulls)20MITPHPPHP &gt;=7.4 &lt;8.6CI passing

Since Jul 12Pushed 2mo ago27 watchersCompare

[ Source](https://github.com/php-lock/lock)[ Packagist](https://packagist.org/packages/malkusch/lock)[ Docs](https://github.com/malkusch/lock)[ RSS](/packages/malkusch-lock/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (10)Dependencies (14)Versions (29)Used By (20)

**[Requirements](#requirements)** | **[Installation](#installation)** | **[Usage](#usage)** | **[Implementations](#implementations)** | **[Authors](#authors)** | **[License](#license)**

php-lock/lock
=============

[](#php-locklock)

[![Latest Stable Version](https://camo.githubusercontent.com/188f3cf697e227aad09a30eb2455a47cdddc99660d0345726a7440ca355fdeaf/68747470733a2f2f706f7365722e707567782e6f72672f6d616c6b757363682f6c6f636b2f76657273696f6e)](https://packagist.org/packages/malkusch/lock)[![Total Downloads](https://camo.githubusercontent.com/0eeb694709214e8e55781d0bcc6717b4731c39ee20da12206215f84b8bf6b963/68747470733a2f2f706f7365722e707567782e6f72672f6d616c6b757363682f6c6f636b2f646f776e6c6f616473)](https://packagist.org/packages/malkusch/lock/stats)[![Build Status](https://github.com/php-lock/lock/actions/workflows/test-unit.yml/badge.svg?branch=master)](https://github.com/php-lock/lock/actions?query=branch:master)[![Coverage](https://camo.githubusercontent.com/b8cf740f2199d26f3b33931569714da0e8e9adad04e3ae5e12f8fa07eb944b65/68747470733a2f2f636f6465636f762e696f2f67682f7068702d6c6f636b2f6c6f636b2f6272616e63682f6d61737465722f67726170682f62616467652e737667)](https://codecov.io/gh/php-lock/lock)[![License](https://camo.githubusercontent.com/f76812d6322750ceaacd3123611e6e6617195f2bd7dedd0378c0c631fd42504e/68747470733a2f2f706f7365722e707567782e6f72672f6d616c6b757363682f6c6f636b2f6c6963656e7365)](https://packagist.org/packages/malkusch/lock)

This library helps executing critical code in concurrent situations in serialized fashion.

php-lock/lock follows [semantic versioning](https://semver.org/).

---

Requirements
------------

[](#requirements)

- PHP 7.4 - 8.5
- Optionally [nrk/predis](https://github.com/nrk/predis) to use the Predis locks.
- Optionally the [php-pcntl](https://php.net/manual/en/book.pcntl.php) 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` or `ext-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, additionally `ext-igbinary` and/or `ext-lzf` have to be installed.

---

Installation
------------

[](#installation)

### Composer

[](#composer)

To use this library through [composer](https://getcomposer.org/), run the following terminal command inside your repository's root folder.

```
composer require malkusch/lock
```

Usage
-----

[](#usage)

This library uses the namespace `Malkusch\Lock`.

### Mutex

[](#mutex)

The [`Malkusch\Lock\Mutex\Mutex`](https://github.com/php-lock/lock/blob/3ca295ccda/src/Mutex/Mutex.php#L15) interface provides the base API for this library.

### Mutex::synchronized()

[](#mutexsynchronized)

[`Malkusch\Lock\Mutex\Mutex::synchronized()`](https://github.com/php-lock/lock/blob/3ca295ccda/src/Mutex/Mutex.php#L38) 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()

[](#mutexcheck)

[`Malkusch\Lock\Mutex\Mutex::check()`](https://github.com/php-lock/lock/blob/3ca295ccda/src/Mutex/Mutex.php#L60) sets a callable, which will be executed when [`Malkusch\Lock\Util\DoubleCheckedLocking::then()`](https://github.com/php-lock/lock/blob/3ca295ccda/src/Util/DoubleCheckedLocking.php#L61) 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](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()`](https://github.com/php-lock/lock/blob/3ca295ccda/src/Util/DoubleCheckedLocking.php#L61) 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()`](https://github.com/php-lock/lock/blob/3ca295ccda/src/Util/DoubleCheckedLocking.php#L61) 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}()

[](#lockreleaseexceptiongetcodeexception-result)

Mutex implementations based on [`Malkush\Lock\Mutex\AbstractLockMutex`](https://github.com/php-lock/lock/blob/3ca295ccda/src/Mutex/AbstractLockMutex.php) will throw [`Malkusch\Lock\Exception\LockReleaseException`](https://github.com/php-lock/lock/blob/3ca295ccda/src/Exception/LockReleaseException.php) 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
---------------

[](#implementations)

You can choose from one of the provided [`Malkusch\Lock\Mutex\Mutex`](#mutex) interface implementations or create/extend your own implementation.

- [`FlockMutex`](#flockmutex)
- [`MemcachedMutex`](#memcachedmutex)
- [`RedisMutex`](#redismutex)
- [`SemaphoreMutex`](#semaphoremutex)
- [`MySQLMutex`](#mysqlmutex)
- [`PostgreSQLMutex`](#postgresqlmutex)
- [`DistributedMutex`](#distributedmutex)

### FlockMutex

[](#flockmutex)

The **FlockMutex** is a lock implementation based on [`flock()`](https://php.net/manual/en/function.flock.php).

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

[](#memcachedmutex)

The **MemcachedMutex** is a spinlock implementation which uses the [`Memcached` extension](https://php.net/manual/en/book.memcached.php).

Example:

```
$memcached = new \Memcached();
$memcached->addServer('localhost', 11211);

$mutex = new MemcachedMutex('balance', $memcached);
```

### RedisMutex

[](#redismutex)

The **RedisMutex** is a lock implementation which supports the [`phpredis` extension](https://github.com/phpredis/phpredis)or [`Predis` API](https://github.com/nrk/predis) 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

[](#semaphoremutex)

The **SemaphoreMutex** is a lock implementation based on [Semaphore](https://php.net/manual/en/ref.sem.php).

Example:

```
$semaphore = sem_get(ftok(__FILE__, 'a'));
$mutex = new SemaphoreMutex($semaphore);
```

### MySQLMutex

[](#mysqlmutex)

The **MySQLMutex** uses MySQL's [`GET_LOCK`](https://dev.mysql.com/doc/refman/9.0/en/locking-functions.html#function_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 &lt; 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

[](#postgresqlmutex)

The **PostgreSQLMutex** uses PostgreSQL's [advisory locking](https://www.postgresql.org/docs/9.4/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS)functions.

Named locks are offered. PostgreSQL locking functions require integers but the conversion is handled automatically.

It supports timeouts. 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

[](#distributedmutex)

The **DistributedMutex** is the distributed lock implementation of [RedLock](https://redis.io/topics/distlock#the-redlock-algorithm) which supports one or more [`Malkush\Lock\Mutex\AbstractSpinlockMutex`](https://github.com/php-lock/lock/blob/3ca295ccda/src/Mutex/AbstractLockMutex.php) instances.

Example:

```
$mutex = new DistributedMutex([
    new \Predis\Client('redis://10.0.0.1'),
    new \Predis\Client('redis://10.0.0.2'),
], 'balance');
```

Authors
-------

[](#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](https://github.com/mvorisek) | [LinkedIn](https://www.linkedin.com/in/mvorisek/).

Commercial support is available.

License
-------

[](#license)

This project is free and is licensed under the MIT.

###  Health Score

75

—

ExcellentBetter than 100% of packages

Maintenance83

Actively maintained with recent releases

Popularity69

Solid adoption and visibility

Community41

Growing community involvement

Maturity91

Battle-tested with a long release history

 Bus Factor2

2 contributors hold 50%+ of commits

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~193 days

Recently: every ~107 days

Total

21

Last Release

88d ago

Major Versions

0.4 → 1.0.02016-08-05

v1.4 → v2.02018-11-08

2.x-dev → 3.0.02024-12-15

PHP version history (7 changes)0.1PHP &gt;=5.5

1.0.0PHP &gt;=5.6

v2.0PHP &gt;=7.1

v2.2PHP ^7.2 || ^8.0

2.3.0PHP &gt;=7.4 &lt;8.4

3.0.1PHP &gt;=7.4 &lt;8.5

3.1.1PHP &gt;=7.4 &lt;8.6

### Community

Maintainers

![](https://www.gravatar.com/avatar/97ee86e5e22b92173b2787cad0ba7ac144109e126221c6d21adecdae32ef37fc?d=identicon)[malkusch](/maintainers/malkusch)

![](https://www.gravatar.com/avatar/23d4c374cd27da6bed534538eb3514a06d2c15485e9d63a8991b277909ecfca8?d=identicon)[willemmollie](/maintainers/willemmollie)

---

Top Contributors

[![willemstuursma](https://avatars.githubusercontent.com/u/701299?v=4)](https://github.com/willemstuursma "willemstuursma (73 commits)")[![mvorisek](https://avatars.githubusercontent.com/u/2228672?v=4)](https://github.com/mvorisek "mvorisek (71 commits)")[![malkusch](https://avatars.githubusercontent.com/u/1623984?v=4)](https://github.com/malkusch "malkusch (64 commits)")[![TheLevti](https://avatars.githubusercontent.com/u/7612582?v=4)](https://github.com/TheLevti "TheLevti (46 commits)")[![vedavith](https://avatars.githubusercontent.com/u/18259805?v=4)](https://github.com/vedavith "vedavith (2 commits)")[![Furgas](https://avatars.githubusercontent.com/u/715407?v=4)](https://github.com/Furgas "Furgas (2 commits)")[![marios88](https://avatars.githubusercontent.com/u/302688?v=4)](https://github.com/marios88 "marios88 (1 commits)")[![colemanator](https://avatars.githubusercontent.com/u/9283606?v=4)](https://github.com/colemanator "colemanator (1 commits)")[![glensc](https://avatars.githubusercontent.com/u/199095?v=4)](https://github.com/glensc "glensc (1 commits)")[![athos-ribeiro](https://avatars.githubusercontent.com/u/2052794?v=4)](https://github.com/athos-ribeiro "athos-ribeiro (1 commits)")[![staabm](https://avatars.githubusercontent.com/u/120441?v=4)](https://github.com/staabm "staabm (1 commits)")

---

Tags

lockmutexphpsemaphoremysqlpostgresqlredissemaphoremutexlockingflockredlockmemcachedlockadvisory-locks

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/malkusch-lock/health.svg)

```
[![Health](https://phpackages.com/badges/malkusch-lock/health.svg)](https://phpackages.com/packages/malkusch-lock)
```

###  Alternatives

[arvenil/ninja-mutex

Simple to use mutex implementation that can use flock, memcache, memcached, mysql or redis for locking

1873.7M27](/packages/arvenil-ninja-mutex)[doctrine/dbal

Powerful PHP database abstraction layer (DBAL) with many features for database schema introspection and management.

9.7k578.4M5.6k](/packages/doctrine-dbal)[symfony/lock

Creates and manages locks, a mechanism to provide exclusive access to a shared resource

514127.6M459](/packages/symfony-lock)[matthiasmullie/scrapbook

Scrapbook is a PHP cache library, with adapters for e.g. Memcached, Redis, Couchbase, APCu, SQL and additional capabilities (e.g. transactions, stampede protection) built on top.

3212.5M32](/packages/matthiasmullie-scrapbook)[desarrolla2/cache

Provides an cache interface for several adapters Apc, Apcu, File, Mongo, Memcache, Memcached, Mysql, Mongo, Redis is supported.

1322.5M47](/packages/desarrolla2-cache)[apix/cache

A thin PSR-6 cache wrapper with a generic interface to various caching backends emphasising cache taggging and indexing to Redis, Memcached, PDO/SQL, APC and other adapters.

114542.8k6](/packages/apix-cache)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
