0 follower

Final Class Yiisoft\Mutex\Synchronizer

InheritanceYiisoft\Mutex\Synchronizer

Executes a callback in synchronized mode, i.e. only a single instance of the callback is executed at the same time:

$synchronizer = new \Yiisoft\Mutex\Synchronizer(new MyMutexFactory());

$newCount = $synchronizer->execute('critical_logic', function () {
    return $counter->increase();
}, 10);

Public Methods

Hide inherited methods

Method Description Defined By
__construct() Yiisoft\Mutex\Synchronizer
execute() Executes a PHP callable with a lock and returns the result. Yiisoft\Mutex\Synchronizer

Method Details

Hide inherited methods

__construct() public method

public mixed __construct ( Yiisoft\Mutex\MutexFactoryInterface $mutexFactory )
$mutexFactory Yiisoft\Mutex\MutexFactoryInterface

                public function __construct(MutexFactoryInterface $mutexFactory)
{
    $this->mutexFactory = $mutexFactory;
}

            
execute() public method

Executes a PHP callable with a lock and returns the result.

public mixed execute ( string $name, callable $callback, integer $timeout 0 )
$name string

Name of the mutex to acquire.

$callback callable

PHP callable to execution.

$timeout integer

Time (in seconds) to wait for lock to be released. Defaults to zero meaning that method {@see \Yiisoft\Mutex\MutexInterface::acquire()} will return false immediately in case lock was already acquired.

return mixed

The result of the PHP callable execution.

throws Yiisoft\Mutex\Exception\MutexLockedException

If unable to acquire lock.

throws Throwable

If an error occurred during the execution of the PHP callable.

                public function execute(string $name, callable $callback, int $timeout = 0)
{
    $mutex = $this->mutexFactory->createAndAcquire($name, $timeout);
    set_error_handler(static function (int $severity, string $message, string $file, int $line): bool {
        if (!(error_reporting() & $severity)) {
            // This error code is not included in error_reporting.
            return true;
        }
        throw new ErrorException($message, $severity, $severity, $file, $line);
    });
    try {
        /** @var mixed $result */
        return $callback();
    } finally {
        restore_error_handler();
        $mutex->release();
    }
}