2017 © Pedro Peláez
 

library lock

Mutex library for exclusive code execution.

image

malkusch/lock

Mutex library for exclusive code execution.

  • Saturday, July 7, 2018
  • by malkusch
  • Repository
  • 21 Watchers
  • 444 Stars
  • 349,255 Installations
  • PHP
  • 10 Dependents
  • 1 Suggesters
  • 39 Forks
  • 3 Open issues
  • 14 Versions
  • 12 % Grown

The README.md

Requirements | Installation | Usage | License and authors | Donations, (*1)

php-lock/lock

Latest Stable Version Total Downloads Latest Unstable Version Build Status License, (*2)

This library helps executing critical code in concurrent situations., (*3)

php-lock/lock follows semantic versioning. Read more on semver.org., (*4)


Requirements

  • PHP 7.1 or above
  • Optionally nrk/predis to use the Predis locks.
  • Optionally the php-pcntl 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

Composer

To use this library through composer, run the following terminal command inside your repository's root folder., (*5)

composer require "malkusch/lock"

Usage

This library uses the namespace malkusch\lock., (*6)

Mutex

The malkusch\lock\mutex\Mutex class is an abstract class and provides the base API for this library., (*7)

Mutex::synchronized()

malkusch\lock\mutex\Mutex::synchronized() 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., (*8)

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., (*9)

Example:, (*10)

$newBalance = $mutex->synchronized(function () use (
    $bankAccount,
    $amount
): int {
    $balance = $bankAccount->getBalance();
    $balance -= $amount;
    if ($balance < 0) {
        throw new \DomainException('You have no credit.');
    }
    $bankAccount->setBalance($balance);

    return $balance;
});

Mutex::check()

malkusch\lock\mutex\Mutex::check() sets a callable, which will be executed when malkusch\lock\util\DoubleCheckedLocking::then() 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., (*11)

See https://en.wikipedia.org/wiki/Double-checked_locking for a more detailed explanation of that feature., (*12)

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() method, will also return false to indicate that the check did not pass either before or after acquiring the lock., (*13)

In the case where the check's callable returns a value other than false, the malkusch\lock\util\DoubleCheckedLocking::then() 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., (*14)

Example:, (*15)

$newBalance = $mutex->check(function () use ($bankAccount, $amount): bool {
    return $bankAccount->getBalance() >= $amount;
})->then(function () use ($bankAccount, $amount): int {
    $balance = $bankAccount->getBalance();
    $balance -= $amount;
    $bankAccount->setBalance($balance);

    return $balance;
});

if (false === $newBalance) {
    if ($balance < 0) {
        throw new \DomainException('You have no credit.');
    }
}

Extracting code result after lock release exception

Mutex implementations based on malkush\lock\mutex\LockMutex will throw [malkusch\lock\exception\LockReleaseException][13] 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., (*16)

Example:, (*17)

try {
    // or $mutex->check(...)
    $result = $mutex->synchronized(function () {
        if (someCondition()) {
            throw new \DomainException();
        }

        return "result";
    });
} catch (LockReleaseException $unlockException) {
    if ($unlockException->getCodeException() !== null) {
        $codeException = $unlockException->getCodeException()
        // do something with the code exception
    } else {
        $code_result = $unlockException->getCodeResult();
        // do something with the code result
    }

    // deal with LockReleaseException or propagate it
    throw $unlockException;
}

Implementations

Because the malkusch\lock\mutex\Mutex class is an abstract class, you can choose from one of the provided implementations or create/extend your own implementation., (*18)

CASMutex

The CASMutex has to be used with a Compare-and-swap operation. This mutex is lock free. It will repeat executing the code until the CAS operation was successful. The code should therefore notify the mutex by calling malkusch\lock\mutex\CASMutex::notify()., (*19)

As the mutex keeps executing the critical code, it must not have any side effects as long as the CAS operation was not successful., (*20)

Example:, (*21)

$mutex = new CASMutex();
$mutex->synchronized(function () use ($memcached, $mutex, $amount): void {
    $balance = $memcached->get("balance", null, $casToken);
    $balance -= $amount;
    if (!$memcached->cas($casToken, "balance", $balance)) {
        return;
    }
    $mutex->notify();
});

FlockMutex

The FlockMutex is a lock implementation based on flock()., (*22)

Example:, (*23)

$mutex = new FlockMutex(fopen(__FILE__, "r"));
$mutex->synchronized(function () use ($bankAccount, $amount) {
    $balance = $bankAccount->getBalance();
    $balance -= $amount;
    if ($balance < 0) {
        throw new \DomainException("You have no credit.");
    }
    $bankAccount->setBalance($balance);
});

Timeouts are supported as an optional second argument. This uses the ext-pcntl extension if possible or busy waiting if not., (*24)

MemcachedMutex

The MemcachedMutex is a spinlock implementation which uses the Memcached API., (*25)

Example:, (*26)

$memcache = new \Memcached();
$memcache->addServer("localhost", 11211);

$mutex = new MemcachedMutex("balance", $memcache);
$mutex->synchronized(function () use ($bankAccount, $amount) {
    $balance = $bankAccount->getBalance();
    $balance -= $amount;
    if ($balance < 0) {
        throw new \DomainException("You have no credit.");
    }
    $bankAccount->setBalance($balance);
});

PHPRedisMutex

The PHPRedisMutex is the distributed lock implementation of RedLock which uses the phpredis extension., (*27)

This implementation requires at least phpredis-2.2.4., (*28)

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., (*29)

Example:, (*30)

$redis = new Redis();
$redis->connect("localhost");

$mutex = new PHPRedisMutex([$redis], "balance");
$mutex->synchronized(function () use ($bankAccount, $amount) {
    $balance = $bankAccount->getBalance();
    $balance -= $amount;
    if ($balance < 0) {
        throw new \DomainException("You have no credit.");
    }
    $bankAccount->setBalance($balance);
});

PredisMutex

The PredisMutex is the distributed lock implementation of RedLock which uses the Predis API., (*31)

Example:, (*32)

$redis = new Client("redis://localhost");

$mutex = new PredisMutex([$redis], "balance");
$mutex->synchronized(function () use ($bankAccount, $amount) {
    $balance = $bankAccount->getBalance();
    $balance -= $amount;
    if ($balance < 0) {
        throw new \DomainException("You have no credit.");
    }
    $bankAccount->setBalance($balance);
});

SemaphoreMutex

The SemaphoreMutex is a lock implementation based on Semaphore., (*33)

Example:, (*34)

$semaphore = sem_get(ftok(__FILE__, "a"));
$mutex = new SemaphoreMutex($semaphore);
$mutex->synchronized(function () use ($bankAccount, $amount) {
    $balance = $bankAccount->getBalance();
    $balance -= $amount;
    if ($balance < 0) {
        throw new \DomainException("You have no credit.");
    }
    $bankAccount->setBalance($balance);
});

TransactionalMutex

The TransactionalMutex delegates the serialization to the DBS. The exclusive code is executed within a transaction. It's up to you to set the correct transaction isolation level. However if the transaction fails (i.e. a PDOException was thrown), the code will be executed again in a new transaction. Therefore the code must not have any side effects besides SQL statements. Also the isolation level should be conserved for the repeated transaction. If the code throws an exception, the transaction is rolled back and not replayed again., (*35)

Example:, (*36)

$mutex = new TransactionalMutex($pdo);
$mutex->synchronized(function () use ($pdo, $accountId, $amount) {
    $select = $pdo->prepare(
        "SELECT balance FROM account WHERE id = ? FOR UPDATE"
    );
    $select->execute([$accountId]);
    $balance = $select->fetchColumn();

    $balance -= $amount;
    if ($balance < 0) {
        throw new \DomainException("You have no credit.");
    }
    $pdo->prepare("UPDATE account SET balance = ? WHERE id = ?")
        ->execute([$balance, $accountId]);
});

MySQLMutex

The MySQLMutex uses MySQL's GET_LOCK function., (*37)

It supports time outs. If the connection to the database server is lost or interrupted, the lock is automatically released., (*38)

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 < 5.7.5., (*39)

$pdo = new PDO("mysql:host=localhost;dbname=test", "username");

$mutex = new MySQLMutex($pdo, "balance", 15);
$mutex->synchronized(function () use ($bankAccount, $amount) {
    $balance = $bankAccount->getBalance();
    $balance -= $amount;
    if ($balance < 0) {
        throw new \DomainException("You have no credit.");
    }
    $bankAccount->setBalance($balance);
});

PgAdvisoryLockMutex

The PgAdvisoryLockMutex uses PostgreSQL's advisory locking functions., (*40)

Named locks are offered. PostgreSQL locking functions require integers but the conversion is handled automatically., (*41)

No time outs are supported. If the connection to the database server is lost or interrupted, the lock is automatically released., (*42)

$pdo = new PDO("pgsql:host=localhost;dbname=test;", "username");

$mutex = new PgAdvisoryLockMutex($pdo, "balance");
$mutex->synchronized(function () use ($bankAccount, $amount) {
    $balance = $bankAccount->getBalance();
    $balance -= $amount;
    if ($balance < 0) {
        throw new \DomainException("You have no credit.");
    }
    $bankAccount->setBalance($balance);
});

License and authors

This project is free and under the WTFPL. Responsible for this project is Willem Stuursma-Ruwen willem@stuursma.name., (*43)

Donations

If you like this project and feel generous donate a few Bitcoins here: 1P5FAZ4QhXCuwYPnLZdk3PJsqePbu1UDDA, (*44)

The Versions

07/07 2018

dev-master

9999999-dev https://github.com/malkusch/lock

Mutex library for exclusive code execution.

  Sources   Download

WTFPL

The Requires

 

The Development Requires

by Willem Stuursma-Ruwen

postgresql redis memcache mysql lock locking mutex semaphore flock cas redlock advisory locks

07/07 2018

dev-16-predis-cluster

dev-16-predis-cluster https://github.com/malkusch/lock

Mutex library for exclusive code execution.

  Sources   Download

WTFPL

The Requires

 

The Development Requires

by Willem Stuursma-Ruwen

postgresql redis memcache mysql lock locking mutex semaphore flock cas redlock advisory locks

07/07 2018

v1.4

1.4.0.0 https://github.com/malkusch/lock

Mutex library for exclusive code execution.

  Sources   Download

WTFPL

The Requires

 

The Development Requires

by Willem Stuursma-Ruwen

postgresql redis memcache mysql lock locking mutex semaphore flock cas redlock advisory locks

26/05 2018

v1.3

1.3.0.0 https://github.com/malkusch/lock

Mutex library for exclusive code execution.

  Sources   Download

WTFPL

The Requires

 

The Development Requires

by Willem Stuursma-Ruwen

redis memcache lock mutex semaphore flock cas redlock

26/05 2018

dev-pgadvisory

dev-pgadvisory https://github.com/malkusch/lock

Mutex library for exclusive code execution.

  Sources   Download

WTFPL

The Requires

 

The Development Requires

by Willem Stuursma-Ruwen

redis memcache lock mutex semaphore flock cas redlock

21/05 2018

v1.2

1.2.0.0 https://github.com/malkusch/lock

Mutex library for exclusive code execution.

  Sources   Download

WTFPL

The Requires

 

The Development Requires

by Willem Stuursma-Ruwen

redis memcache lock mutex semaphore flock cas redlock

15/04 2018

v1.1

1.1.0.0 https://github.com/malkusch/lock

Mutex library for exclusive code execution.

  Sources   Download

WTFPL

The Requires

 

The Development Requires

by Willem Stuursma-Ruwen

redis memcache lock mutex semaphore flock cas redlock

22/11 2016

dev-6-flock-timeout

dev-6-flock-timeout https://github.com/malkusch/lock

Mutex library for exclusive code execution.

  Sources   Download

WTFPL

The Requires

 

The Development Requires

redis memcache lock mutex semaphore flock cas redlock

05/08 2016

1.0.0

1.0.0.0 https://github.com/malkusch/lock

Mutex library for exclusive code execution.

  Sources   Download

WTFPL

The Requires

 

The Development Requires

redis memcache lock mutex semaphore flock cas redlock

11/08 2015

0.4

0.4.0.0 https://github.com/malkusch/lock

Mutex library for exclusive code execution.

  Sources   Download

WTFPL

The Requires

 

The Development Requires

redis memcache lock mutex semaphore flock cas redlock

31/07 2015

0.3

0.3.0.0 https://github.com/malkusch/lock

Mutex library for locked code execution.

  Sources   Download

WTFPL

The Requires

 

The Development Requires

lock mutex semaphore flock

27/07 2015

0.2.1

0.2.1.0 https://github.com/malkusch/lock

Mutex library for locked code execution.

  Sources   Download

WTFPL

The Requires

  • php >=5.5

 

The Development Requires

lock mutex semaphore flock

24/07 2015

0.2

0.2.0.0 https://github.com/malkusch/lock

Mutex library for locked code execution.

  Sources   Download

WTFPL

The Requires

  • php >=5.5

 

The Development Requires

lock mutex semaphore flock

12/07 2015

0.1

0.1.0.0 https://github.com/malkusch/lock

Mutex library for locked code execution.

  Sources   Download

WTFPL

The Requires

  • php >=5.5

 

The Development Requires

lock mutex flock