Locker Coroutine Lock

Locker is a type of memory lock used for synchronization between coroutines. It is commonly used to queue access to a critical resource in a coroutine, such as a database component that does not implement a connection pool. Locker can be used to queue access to that component, preventing data anomalies caused by multiple coroutines simultaneously using the same connection resource.

Tip
This feature requires workerman>=5.1.0

Note

  • Locker supports Swoole/Swow/Fiber/Select/Event-driven architectures.
  • Locker is used for mutual exclusion access to a resource among different coroutines within the same process; it is not affected by other processes.
<?php
use Workerman\Connection\TcpConnection;
use Workerman\Coroutine\Locker;
use Workerman\Events\Swoole;
use Workerman\Protocols\Http\Request;
use Workerman\Worker;
require_once __DIR__ . '/vendor/autoload.php';

$worker = new Worker('http://0.0.0.0:8001');

$worker->eventLoop = Swoole::class; // Or Swow::class or Fiber::class

$worker->onMessage = function (TcpConnection $connection, Request $request) {
    static $redis;
    if (!$redis) {
        $redis = new Redis();
        $redis->connect('127.0.0.1', 6379);
    }
    // Avoid multiple coroutines using the same connection simultaneously, causing errors like "Socket#10 has already been bound to another coroutine"
    Locker::lock('redis');
    $time = $redis->time();
    Locker::unlock('redis');
    $connection->send(json_encode($time));
};

Worker::runAll();

Interface Description

interface LockerInterface
{
    /**
     * Lock
     */
    public static function lock(string $key): bool

    /**
     * Unlock
     */
    public static function unlock(string $key): bool
}