Lock

Lock can be used for data synchronization between multiple processes.

Locks should not be used within coroutine context.

Methods

  • Swoole\Lock->__construct
  • Swoole\Lock->lock
  • Swoole\Lock->lockwait
  • Swoole\Lock->trylock
  • Swoole\Lock->lock_read
  • Swoole\Lock->trylock_read
  • Swoole\Lock->unlock

    Lock types:

    SWOOLE_FILELOCK
    SWOOLE_RWLOCK
    SWOOLE_SEM
    SWOOLE_MUTEX
    SWOOLE_SPINLOCK

    Example:

    <?php
    
    $lock = new Swoole\Lock(SWOOLE_MUTEX);
    echo "[Master] Create lock\n";
    $lock->lock();
    if (pcntl_fork() > 0)
    {
        sleep(1);
        $lock->unlock();
    } 
    else
    {
        echo "[Child] Wait Lock\n";
        $lock->lock();
        echo "[Child] Get Lock\n";
        $lock->unlock();
        exit("[Child] exit\n");
    }
    echo "[Master]release lock\n";
    unset($lock);
    sleep(1);
    echo "[Master]exit\n";