Lock

4.x is outdated, please check the latest version 22.x


Latest version: pecl install openswoole-22.1.2

Lock can be used for data synchronization between multiple processes.

Locks should not be used within coroutine context.

Methods

Lock types:

ConstantDescription
SWOOLE_FILELOCKfile lock
SWOOLE_RWLOCKread write lock
SWOOLE_SEMLinux semaphore
SWOOLE_MUTEXMutex
SWOOLE_SPINLOCKspin lock

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";
Last updated on August 31, 2022