Swoole Lock

Swoole locks enable PHP developers use locks for data synchronization between multiple theads or processes.

Lock types:

public Swoole\Lock::__construct ([ string $type [, string $file_lock_location ]] )

Alias: swoole_lock->__construct($type, $file_lock_location = '/tmp/file.lock');

Construct a lock.

public void Swoole\Lock::__destruct ( void )

Alias: swoole_lock->__destruct();

Destory a lock.

public void Swoole\Lock::lock ( void )

Alias: swoole_lock->lock();

Try to acquire the lock. It will block if the lock is not available.

public void Swoole\Lock::lockwait ( integer $timeout = 1 )

Alias: swoole_lock->lockwait($timeout = 1);

Try to acquire the lock and waiting the lock for a duration before giving up.

public void Swoole\Lock::trylock ( void )

Alias: swoole_lock->trylock();

Try to acquire the lock and return straight away even the lock is not available.

public void Swoole\Lock::lock_read ( void )

Alias: swoole_lock->lock_read();

Lock a read-write lock for reading.

public void Swoole\Lock::trylock_read ( void )

Alias: swoole_lock->trylock_read();

Try to lock a read-write lock for reading and return straight away even the lock is not available.

public void Swoole\Lock::unlock ( void )

Alias: swoole_lock->unlock();

Release the 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";