yiisoft / mutex
Yii Mutex 库
1.1.1
2022-01-12 09:35 UTC
Requires
- php: ^7.4|^8.0
Requires (Dev)
- phpunit/phpunit: ^9.5
- roave/infection-static-analysis-plugin: ^1.14
- spatie/phpunit-watcher: ^1.23
- vimeo/psalm: ^4.9
Suggests
- yiisoft/mutex-file: Use the File driver for mutex
- yiisoft/mutex-pdo-mysql: Use the MySQL PDO driver for mutex
- yiisoft/mutex-pdo-oracle: Use the Oracle PDO driver for mutex
- yiisoft/mutex-pdo-pgsql: Use the Postgres PDO driver for mutex
- yiisoft/mutex-redis: Use the Redis driver for mutex
This package is auto-updated.
Last update: 2024-09-20 11:03:07 UTC
README
Yii Mutex
此包提供互斥锁实现,允许并发进程互斥执行,以防止“竞态条件”。
这是通过使用“锁”机制实现的。每个可能的并发进程在访问相应数据之前都会通过获取锁来协作。
要求
- PHP 7.4 或更高版本。
安装
可以使用Composer安装此包
composer require yiisoft/mutex
通用用法
您可以使用多种方式使用此包。您可以在同步模式下执行回调,即同一时间只能执行单个回调实例
/** @var \Yiisoft\Mutex\Synchronizer $synchronizer */ $newCount = $synchronizer->execute('critical', function () { return $counter->increase(); }, 10);
另一种方法是手动打开和关闭互斥锁
/** @var \Yiisoft\Mutex\SimpleMutex $simpleMutex */ if (!$simpleMutex->acquire('critical', 10)) { throw new \Yiisoft\Mutex\Exception\MutexLockedException('Unable to acquire the "critical" mutex.'); } $newCount = $counter->increase(); $simpleMutex->release('critical');
这可以在较低级别完成
/** @var \Yiisoft\Mutex\MutexFactoryInterface $mutexFactory */ $mutex = $mutexFactory->createAndAcquire('critical', 10); $newCount = $counter->increase(); $mutex->release();
如果您想要更多控制,您可以手动获取互斥锁
/** @var \Yiisoft\Mutex\MutexFactoryInterface $mutexFactory */ $mutex = $mutexFactory->create('critical'); if (!$mutex->acquire(10)) { throw new \Yiisoft\Mutex\Exception\MutexLockedException('Unable to acquire the "critical" mutex.'); } $newCount = $counter->increase(); $mutex->release();
互斥锁驱动程序
有一些互斥锁驱动程序作为独立包提供
如果您想提供自己的驱动程序,您需要实现MutexFactoryInterface
和MutexInterface
。有可扩展的Mutex
,MutexFactory
和一个包含retryAcquire()
方法的RetryAcquireTrait
,该方法是实现“等待锁一段时间”功能的。
在实现自己的驱动程序时,您需要确保自动解锁。例如,使用析构函数
public function __destruct() { $this->release(); }
和关闭函数
public function __construct() { register_shutdown_function(function () { $this->release(); }); }
请注意,您不应在析构函数或关闭函数中调用exit()
或die()
函数。因为在析构函数和关闭函数中调用这些函数将防止所有后续的完成函数执行。
文档
如果您需要帮助或有问题,Yii 论坛是一个很好的地方。您还可以查看其他Yii 社区资源。
许可证
Yii Mutex 是免费软件。它根据BSD许可证发布。有关更多信息,请参阅LICENSE
。
由Yii 软件维护。