{"id":13462387,"url":"https://github.com/php-lock/lock","last_synced_at":"2025-05-13T20:11:53.713Z","repository":{"id":1070893,"uuid":"38968462","full_name":"php-lock/lock","owner":"php-lock","description":"Popular PHP library for serialized execution of critical code in concurrent situations","archived":false,"fork":false,"pushed_at":"2025-04-06T08:28:17.000Z","size":495,"stargazers_count":941,"open_issues_count":3,"forks_count":88,"subscribers_count":27,"default_branch":"master","last_synced_at":"2025-04-09T01:18:49.394Z","etag":null,"topics":["lock","mutex","php","semaphore"],"latest_commit_sha":null,"homepage":"","language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/php-lock.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2015-07-12T16:17:29.000Z","updated_at":"2025-04-06T08:28:21.000Z","dependencies_parsed_at":"2024-06-18T10:57:42.009Z","dependency_job_id":"d7c441f7-80bd-4b84-a701-fce95ee30dab","html_url":"https://github.com/php-lock/lock","commit_stats":{"total_commits":207,"total_committers":10,"mean_commits":20.7,"dds":0.6570048309178744,"last_synced_commit":"63c1b268f521a702cb8755ed92631c1fac1775e6"},"previous_names":[],"tags_count":25,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/php-lock%2Flock","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/php-lock%2Flock/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/php-lock%2Flock/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/php-lock%2Flock/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/php-lock","download_url":"https://codeload.github.com/php-lock/lock/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":251299573,"owners_count":21567249,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["lock","mutex","php","semaphore"],"created_at":"2024-07-31T12:00:46.671Z","updated_at":"2025-04-28T10:49:59.733Z","avatar_url":"https://github.com/php-lock.png","language":"PHP","funding_links":[],"categories":["Uncategorized","目录","Table of Contents","PHP","Configuration"],"sub_categories":["Uncategorized","缓存和锁定 Caching and Locking","Caching and Locking","Miscellaneous"],"readme":"**[Requirements](#requirements)** |\n**[Installation](#installation)** |\n**[Usage](#usage)** |\n**[Implementations](#implementations)** |\n**[Authors](#authors)** |\n**[License](#license)**\n\n# php-lock/lock\n\n[![Latest Stable Version](https://poser.pugx.org/malkusch/lock/version)](https://packagist.org/packages/malkusch/lock)\n[![Total Downloads](https://poser.pugx.org/malkusch/lock/downloads)](https://packagist.org/packages/malkusch/lock/stats)\n[![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)\n[![License](https://poser.pugx.org/malkusch/lock/license)](https://packagist.org/packages/malkusch/lock)\n\nThis library helps executing critical code in concurrent situations in serialized fashion.\n\nphp-lock/lock follows [semantic versioning][1].\n\n----\n\n## Requirements\n\n - PHP 7.4 - 8.4\n - Optionally [nrk/predis][2] to use the Predis locks.\n - Optionally the [php-pcntl][3] extension to enable locking with `flock()`\n   without busy waiting in CLI scripts.\n - Optionally `flock()`, `ext-redis`, `ext-pdo_mysql`, `ext-pdo_sqlite`,\n   `ext-pdo_pgsql` or `ext-memcached` can be used as a backend for locks. See\n   examples below.\n - If `ext-redis` is used for locking and is configured to use igbinary for\n   serialization or lzf for compression, additionally `ext-igbinary` and/or\n   `ext-lzf` have to be installed.\n\n----\n\n## Installation\n\n### Composer\n\nTo use this library through [composer][4], run the following terminal command\ninside your repository's root folder.\n\n```sh\ncomposer require malkusch/lock\n```\n\n## Usage\n\nThis library uses the namespace `Malkusch\\Lock`.\n\n### Mutex\n\nThe [`Malkusch\\Lock\\Mutex\\Mutex`][5] interface provides the base API for this library.\n\n### Mutex::synchronized()\n\n[`Malkusch\\Lock\\Mutex\\Mutex::synchronized()`][6] executes code exclusively. This\nmethod guarantees that the code is only executed by one process at once. Other\nprocesses have to wait until the mutex is available. The critical code may throw\nan exception, which would release the lock as well.\n\nThis method returns whatever is returned to the given callable. The return\nvalue is not checked, thus it is up to the user to decide if for example the\nreturn value `false` or `null` should be seen as a failed action.\n\nExample:\n\n```php\n$newBalance = $mutex-\u003esynchronized(static function () use ($bankAccount, $amount) {\n    $balance = $bankAccount-\u003egetBalance();\n    $balance -= $amount;\n    if ($balance \u003c 0) {\n        throw new \\DomainException('You have no credit');\n    }\n    $bankAccount-\u003esetBalance($balance);\n\n    return $balance;\n});\n```\n\n### Mutex::check()\n\n[`Malkusch\\Lock\\Mutex\\Mutex::check()`][7] sets a callable, which will be\nexecuted when [`Malkusch\\Lock\\Util\\DoubleCheckedLocking::then()`][8] is called,\nand performs a double-checked locking pattern, where it's return value decides\nif the lock needs to be acquired and the synchronized code to be executed.\n\nSee [https://en.wikipedia.org/wiki/Double-checked_locking][9] for a more\ndetailed explanation of that feature.\n\nIf the check's callable returns `false`, no lock will be acquired and the\nsynchronized code will not be executed. In this case the\n[`Malkusch\\Lock\\Util\\DoubleCheckedLocking::then()`][8] method, will also return\n`false` to indicate that the check did not pass either before or after acquiring\nthe lock.\n\nIn the case where the check's callable returns a value other than `false`, the\n[`Malkusch\\Lock\\Util\\DoubleCheckedLocking::then()`][8] method, will\ntry to acquire the lock and on success will perform the check again. Only when\nthe check returns something other than `false` a second time, the synchronized\ncode callable, which has been passed to `then()` will be executed. In this case\nthe return value of `then()` will be what ever the given callable returns and\nthus up to the user to return `false` or `null` to indicate a failed action as\nthis return value will not be checked by the library.\n\nExample:\n\n```php\n$newBalance = $mutex-\u003echeck(static function () use ($bankAccount, $amount): bool {\n    return $bankAccount-\u003egetBalance() \u003e= $amount;\n})-\u003ethen(static function () use ($bankAccount, $amount) {\n    $balance = $bankAccount-\u003egetBalance();\n    $balance -= $amount;\n    $bankAccount-\u003esetBalance($balance);\n\n    return $balance;\n});\n```\n\n### LockReleaseException::getCode{Exception, Result}()\n\nMutex implementations based on [`Malkush\\Lock\\Mutex\\AbstractLockMutex`][10] will throw\n[`Malkusch\\Lock\\Exception\\LockReleaseException`][11] in case of lock release\nproblem, but the synchronized code block will be already executed at this point.\nIn order to read the code result (or an exception thrown there),\n`LockReleaseException` provides methods to extract it.\n\nExample:\n```php\ntry {\n    $result = $mutex-\u003esynchronized(static function () {\n        if (someCondition()) {\n            throw new \\DomainException();\n        }\n\n        return 'result';\n    });\n} catch (LockReleaseException $e) {\n    if ($e-\u003egetCodeException() !== null) {\n        // do something with the $e-\u003egetCodeException() exception\n    } else {\n        // do something with the $e-\u003egetCodeResult() result\n    }\n\n    throw $e;\n}\n```\n\n## Implementations\n\nYou can choose from one of the provided [`Malkusch\\Lock\\Mutex\\Mutex`](#mutex) interface\nimplementations or create/extend your own implementation.\n\n- [`FlockMutex`](#flockmutex)\n- [`MemcachedMutex`](#memcachedmutex)\n- [`RedisMutex`](#redismutex)\n- [`SemaphoreMutex`](#semaphoremutex)\n- [`MySQLMutex`](#mysqlmutex)\n- [`PostgreSQLMutex`](#postgresqlmutex)\n- [`DistributedMutex`](#distributedmutex)\n\n### FlockMutex\n\nThe **FlockMutex** is a lock implementation based on\n[`flock()`](https://php.net/manual/en/function.flock.php).\n\nExample:\n```php\n$mutex = new FlockMutex(fopen(__FILE__, 'r'));\n```\n\nTimeouts are supported as an optional second argument. This uses the `ext-pcntl`\nextension if possible or busy waiting if not.\n\n### MemcachedMutex\n\nThe **MemcachedMutex** is a spinlock implementation which uses the\n[`Memcached` extension](https://php.net/manual/en/book.memcached.php).\n\nExample:\n```php\n$memcached = new \\Memcached();\n$memcached-\u003eaddServer('localhost', 11211);\n\n$mutex = new MemcachedMutex('balance', $memcached);\n```\n\n### RedisMutex\n\nThe **RedisMutex** is a lock implementation which supports the\n[`phpredis` extension](https://github.com/phpredis/phpredis)\nor [`Predis` API](https://github.com/nrk/predis) clients.\n\nBoth Redis and Valkey servers are supported.\n\nIf used with a cluster of Redis servers, acquiring and releasing locks will\ncontinue to function as long as a majority of the servers still works.\n\nExample:\n```php\n$redis = new \\Redis();\n$redis-\u003econnect('localhost');\n// OR $redis = new \\Predis\\Client('redis://localhost');\n\n$mutex = new RedisMutex($redis, 'balance');\n```\n\n### SemaphoreMutex\n\nThe **SemaphoreMutex** is a lock implementation based on\n[Semaphore](https://php.net/manual/en/ref.sem.php).\n\nExample:\n```php\n$semaphore = sem_get(ftok(__FILE__, 'a'));\n$mutex = new SemaphoreMutex($semaphore);\n```\n\n### MySQLMutex\n\nThe **MySQLMutex** uses MySQL's\n[`GET_LOCK`](https://dev.mysql.com/doc/refman/9.0/en/locking-functions.html#function_get-lock)\nfunction.\n\nBoth MySQL and MariaDB servers are supported.\n\nIt supports timeouts. If the connection to the database server is lost or\ninterrupted, the lock is automatically released.\n\nNote that before MySQL 5.7.5 you cannot use nested locks, any new lock will\nsilently release already held locks. You should probably refrain from using this\nmutex on MySQL versions \u003c 5.7.5.\n\nAlso note that `GET_LOCK` function is server wide and the MySQL manual suggests\nyou to namespace your locks like `dbname.lockname`.\n\n```php\n$pdo = new \\PDO('mysql:host=localhost;dbname=test', 'username');\n$mutex = new MySQLMutex($pdo, 'balance', 15);\n```\n\n### PostgreSQLMutex\n\nThe **PostgreSQLMutex** uses PostgreSQL's\n[advisory locking](https://www.postgresql.org/docs/9.4/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS)\nfunctions.\n\nNamed locks are offered. PostgreSQL locking functions require integers but the\nconversion is handled automatically.\n\nNo timeouts are supported. If the connection to the database server is lost or\ninterrupted, the lock is automatically released.\n\n```php\n$pdo = new \\PDO('pgsql:host=localhost;dbname=test', 'username');\n$mutex = new PostgreSQLMutex($pdo, 'balance');\n```\n\n### DistributedMutex\n\nThe **DistributedMutex** is the distributed lock implementation of\n[RedLock](https://redis.io/topics/distlock#the-redlock-algorithm) which supports\none or more [`Malkush\\Lock\\Mutex\\AbstractSpinlockMutex`][10] instances.\n\nExample:\n```php\n$mutex = new DistributedMutex([\n    new \\Predis\\Client('redis://10.0.0.1'),\n    new \\Predis\\Client('redis://10.0.0.2'),\n], 'balance');\n```\n\n## Authors\n\nSince year 2015 the development was led by Markus Malkusch, Willem Stuursma-Ruwen and many GitHub contributors.\n\nCurrently this library is maintained by Michael Voříšek - [GitHub](https://github.com/mvorisek) | [LinkedIn](https://www.linkedin.com/in/mvorisek/).\n\nCommercial support is available.\n\n## License\n\nThis project is free and is licensed under the MIT.\n\n[1]: https://semver.org/\n[2]: https://github.com/nrk/predis\n[3]: https://php.net/manual/en/book.pcntl.php\n[4]: https://getcomposer.org/\n[5]: https://github.com/php-lock/lock/blob/3ca295ccda/src/Mutex/Mutex.php#L15\n[6]: https://github.com/php-lock/lock/blob/3ca295ccda/src/Mutex/Mutex.php#L38\n[7]: https://github.com/php-lock/lock/blob/3ca295ccda/src/Mutex/Mutex.php#L60\n[8]: https://github.com/php-lock/lock/blob/3ca295ccda/src/Util/DoubleCheckedLocking.php#L61\n[9]: https://en.wikipedia.org/wiki/Double-checked_locking\n[10]: https://github.com/php-lock/lock/blob/3ca295ccda/src/Mutex/AbstractLockMutex.php\n[11]: https://github.com/php-lock/lock/blob/3ca295ccda/src/Exception/LockReleaseException.php\n[12]: https://github.com/php-lock/lock/blob/41509dda0a/src/Mutex/AbstractSpinlockMutex.php#L15\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fphp-lock%2Flock","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fphp-lock%2Flock","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fphp-lock%2Flock/lists"}