Mastering Swoole Locks in PHP: Types, Methods, and Practical Examples

This guide explains how to use Swoole\Lock in PHP, covering the five supported lock types, constructor parameters, key methods such as lock, unlock, trylock, lockwait, and lock_read, along with best‑practice warnings and a complete example demonstrating inter‑process synchronization.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
Mastering Swoole Locks in PHP: Types, Methods, and Practical Examples

Swoole provides a Swoole\Lock class that enables easy creation of locks for data synchronization in PHP, supporting five lock types: SWOOLE_FILELOCK (file lock), SWOOLE_RWLOCK (read‑write lock), SWOOLE_SEM (semaphore), SWOOLE_MUTEX (mutex), and SWOOLE_SPINLOCK (spin lock).

Important warning: Do not create lock objects inside callbacks such as onReceive, because the lock will remain in memory and cause a memory leak.

The constructor signature is

Swoole\Lock->__construct(int $type = SWOOLE_MUTEX, string $lockfile = '')

. When using SWOOLE_FILELOCK, the $lockfile parameter must specify the lock file path; other types ignore this argument. The default lock type is SWOOLE_MUTEX.

lock() : Blocks until the lock is acquired; returns true on success.

unlock() : Releases the lock; returns true on success.

trylock() : Non‑blocking attempt to acquire the lock; returns true if successful, otherwise false. (Not available for SWOOLE_SEM.)

lockwait(float $timeout = 1.0) : Like lock() but with a timeout in seconds (supports floating‑point values). Returns true if the lock is obtained within the timeout, otherwise false. Only SWOOLE_MUTEX supports this.

lock_read() : Acquires a read lock (shared lock). Only SWOOLE_RWLOCK and SWOOLE_FILELOCK support read locks. Other processes can still obtain read locks concurrently, but exclusive locks ( lock() or trylock()) block all other lock attempts.

trylock_read() : Non‑blocking version of lock_read(); returns true on success, false otherwise.

Below is a complete example that creates a mutex lock, forks a child process, and demonstrates lock acquisition, release, and proper cleanup:

<?php
$lock = new Swoole\Lock(SWOOLE_MUTEX);

echo "[Master]create lock
";
$lock->lock();

if (pcntl_fork() > 0) {
    // Parent process
    sleep(1);
    $lock->unlock();
} else {
    // Child process
    echo "[Child] Wait Lock
";
    $lock->lock();
    echo "[Child] Get Lock
";
    $lock->unlock();
    exit("[Child] exit
");
}

echo "[Master]release lock
";
unset($lock);
sleep(1);
echo "[Master]exit
";
?>

The example shows how the parent holds the lock while the child blocks on lock(), then proceeds after the parent releases it. It also demonstrates proper destruction of the lock object with unset() to avoid memory leaks.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendconcurrencySynchronizationPHPLockSwoole
Laravel Tech Community
Written by

Laravel Tech Community

Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.