Coder Social home page Coder Social logo

mutex's Introduction

Yii

Yii Mutex


Latest Stable Version Total Downloads Build status Scrutinizer Code Quality Code Coverage Mutation testing badge static analysis type-coverage

This package provides mutex implementation and allows mutual execution of concurrent processes in order to prevent "race conditions".

This is achieved by using a "lock" mechanism. Each possibly concurrent processes cooperates by acquiring a lock before accessing the corresponding data.

Requirements

  • PHP 7.4 or higher.

Installation

The package could be installed with Composer:

composer require yiisoft/mutex

General usage

There are multiple ways you can use the package. You can execute a callback in a synchronized mode i.e. only a single instance of the callback is executed at the same time:

/** @var \Yiisoft\Mutex\Synchronizer $synchronizer */
$newCount = $synchronizer->execute('critical', function () {
    return $counter->increase();
}, 10);

Another way is to manually open and close mutex:

/** @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');

It could be done on lower level:

/** @var \Yiisoft\Mutex\MutexFactoryInterface $mutexFactory */
$mutex = $mutexFactory->createAndAcquire('critical', 10);
$newCount = $counter->increase();
$mutex->release();

And if you want even more control, you can acquire mutex manually:

/** @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();

Mutex drivers

There are some mutex drivers available as separate packages:

If you want to provide your own driver, you need to implement MutexFactoryInterface and MutexInterface. There is ready to extend Mutex, MutexFactory and a RetryAcquireTrait that contains retryAcquire() method implementing the "wait for a lock for a certain time" functionality.

When implementing your own drivers, you need to take care of automatic unlocking. For example using a destructor:

public function __destruct()
{
    $this->release();
}

and shutdown function:

public function __construct()
{
    register_shutdown_function(function () {
        $this->release();
    });
}

Note that you should not call the exit() or die() functions in the destructor or shutdown function. Since calling these functions in the destructor and shutdown function will prevent all subsequent completion functions from executing.

Documentation

If you need help or have a question, the Yii Forum is a good place for that. You may also check out other Yii Community Resources.

License

The Yii Mutex is free software. It is released under the terms of the BSD License. Please see LICENSE for more information.

Maintained by Yii Software.

Support the project

Open Collective

Follow updates

Official website Twitter Telegram Facebook Slack

mutex's People

Contributors

arhell avatar dependabot-preview[bot] avatar dependabot[bot] avatar devanych avatar fantom409 avatar hiqsol avatar loveorigami avatar luizcmarin avatar machour avatar rob006 avatar roxblnfk avatar samdark avatar terabytesoftw avatar viktorprogger avatar vjik avatar xepozz avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

mutex's Issues

update irc link

What steps will reproduce the problem?

What is the expected result?

What do you get instead?

Additional info

Q A
Version 1.0.?
PHP version
Operating system

Release mutex anyway despite autocommit option

Now every mutex driver must release mutex manually if option autocommit set on true.

This decision not only adds difficulties in implementing the new driver, but also does not eliminate problems when managing the mutex.

Imagine that you have some acquired mutex:

$fileMutexFactory = new FileMutexFactory(__DIR__ . '/var/mutexes', false);

$mutex = $this->mutexes->create('some_mutex');

// some actions

$this->doSomething(); // But there will be exception

$mutex->release();

Such mutex will not be released because autocommit turn off.

I think, mutex releaser must be required and do not rely on the user's actions. Every mutex implementation must release mutex anyway in they destructor's.

The following code will guarantees that the mutex will be released anyway on the script shutdown, and it also does not require drivers to implement it themselves.

abstract class Mutex
{
       /**
     * Acquires a lock.
     *
     * @param int $timeout Time (in seconds) to wait for lock to be released. Defaults to zero meaning that method
     * will return false immediately in case lock was already acquired.
     */
    abstract public function acquire(int $timeout = 0): bool;

    /**
     * Releases a lock.
     */
    abstract public function release(): void;

    abstract public function released(): bool;

    final public function __destruct()
    {
       if (!$this->released()) {
           $this->release();
       }
    }
}

After that, we can delete the call to the register_shutdown_function function and the `autocommit' option.

Allow microseconds (float?) as timeout

Good day. It not nessesery, but how about add microseconds as timeout - as additional argument or change current type to float? For example (my case) it can be used for some external API with limited requests per second. Thanks

The exception thrown, when the mutex acquire fails, is too generic

When the Yiisoft\Mutex\MutexFactory::createAndAcquire() method fails to acquire lock the \RuntimeException is thrown.
Lets say you have code:

 try {
     $this->synchronizer->execute(
         'myMutex',
         function () {
             // do some synchronized logic
         },
         30
    );
} catch (\RuntimeException $ex) {
    // handle exception
}

The issue with this code is that \RuntimeException is too generic and can easily be thrown from inside the synchronized logic too. You can't easily setup the try-catch block to catch only exception caused by failed attempt to acquire mutex.
The use case when you would need to do that might be when you want to show some output to user when the mutex is not acquired. For example something like "The work is in progress. Please try again later."

It would be much easier to do if the exception thrown is something like this

class MutexException extends RuntimeException

Handling exception while mutex is acquired implicitly

What steps will reproduce the problem?

If exception will be thrown from callback here, mutex will not be released and nobody else will be able to acquire it.

What is the expected result?

Expected exception handling.

$mutex = $this->mutexFactory->createAndAcquire($name, $timeout);

try {
     /** @var mixed */
     return $callback();
} catch (\Throwable $throwable) {
     throw $throwable;
} finally {
   $mutex->release();
}

Additional info

Q A
Version 1.0.?
PHP version any
Operating system doesn't matter

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.