Locks and synchronization

suggest change

In concurrent and distributed computing, locking and synchronization prevent race conditions and ensure data consistency when multiple processes, threads, or web requests attempt to access shared resources simultaneously. Because standard PHP operates on a share-nothing architecture per request, synchronization is typically achieved using file locks (flock), System V semaphores, thread-level synchronization primitives, distributed locks (such as Redis), or database locks.


1. Advisory File Locking with flock

The built-in flock() function provides operating-system-level advisory locking on open file handles. This is the simplest and most portable synchronization mechanism in standard PHP—commonly used to ensure only one instance of a cron script runs at a time.

Exclusive Non-Blocking Lock (CLI Single-Instance)

<?php

$lockFile = fopen('/tmp/daily_report.lock', 'c+');

if (!$lockFile) {
    die("Failed to open lock file.\n");
}

// Attempt an exclusive lock without blocking (LOCK_EX | LOCK_NB)
if (!flock($lockFile, LOCK_EX | LOCK_NB)) {
    echo "Another instance of this process is already running. Exiting.\n";
    exit(0);
}

try {
    echo "Lock acquired! Running critical batch process...\n";
    // Simulate long-running task
    sleep(5);
} finally {
    // Always release the lock and close file handle
    flock($lockFile, LOCK_UN);
    fclose($lockFile);
    echo "Lock released.\n";
}

Locking Modes

Constant Description
LOCK_SH Shared lock: Allows multiple readers, blocks writers
LOCK_EX Exclusive lock: Only one process can hold the lock; blocks both readers and writers
LOCK_UN Unlock: Releases an active shared or exclusive lock
LOCK_NB Non-blocking: Combine with LOCK_SH or LOCK_EX via bitwise OR (|) to return immediately instead of waiting

2. System V Semaphores (sysvsem)

When running on Linux/Unix systems with the sysvsem extension enabled, PHP can synchronize processes using kernel-level IPC semaphores:

<?php

// Generate a unique System V IPC key from a pathname and project identifier
$key = ftok(__FILE__, 'L');

// Acquire a semaphore with max 1 concurrent acquisition (binary semaphore / mutex)
$semId = sem_get($key, 1, 0666, true);

if (!$semId) {
    die("Could not obtain semaphore.\n");
}

echo "Waiting to acquire semaphore...\n";
sem_acquire($semId); // Blocks until the semaphore is available

try {
    echo "Entered critical section!\n";
    // Perform shared resource update
    sleep(2);
} finally {
    sem_release($semId);
    echo "Left critical section, semaphore released.\n";
}

3. Thread Synchronization (pthreads and parallel)

When using multi-threaded PHP extensions such as parallel or pthreads, multiple threads share the same process memory space.

Thread Safety with parallel\Sync

The modern parallel extension provides parallel\Sync to coordinate and synchronize state across worker threads:

<?php

use parallel\Runtime;
use parallel\Sync;

$sync = new Sync(0); // Shared state counter

$runtime = new Runtime();

// Run concurrent worker
$future = $runtime->run(function(Sync $sync) {
    // Invoking the Sync object runs the callable while holding its mutex
    $sync(function() use ($sync) {
        $sync->set($sync->get() + 10);
    });
}, [$sync]);

$future->value(); // Wait for the worker to finish

// Main thread access
echo "Current synchronized value: " . $sync->get() . "\n"; // 10

4. Distributed Locks with Redis

In horizontally scaled environments where multiple PHP web servers or background workers run on different machines, local file locks or semaphores do not work across servers. A central data store like Redis provides fast, distributed locking.

Safe Redis Lock with Expiration and Token Verification

A robust distributed lock must:

  1. Set the key atomically only if it does not already exist (NX).
  2. Include an automatic TTL (PX) to avoid permanent deadlocks if a worker crashes.
  3. Verify that the releasing worker holds the matching random token before unlocking.
<?php

class RedisLock
{
    private Redis $redis;
    private string $resource;
    private ?string $token = null;
    private int $ttlMs;

    public function __construct(Redis $redis, string $resource, int $ttlMs = 5000)
    {
        $this->redis = $redis;
        $this->resource = "lock:" . $resource;
        $this->ttlMs = $ttlMs;
    }

    public function acquire(): bool
    {
        $this->token = bin2hex(random_bytes(16));

        // Atomic SET if Not Exists with millisecond expiration
        $acquired = $this->redis->set(
            $this->resource,
            $this->token,
            ['NX', 'PX' => $this->ttlMs]
        );

        return $acquired === true;
    }

    public function release(): bool
    {
        if ($this->token === null) {
            return false;
        }

        // Lua script ensures atomic check-and-delete
        $lua = '
            if redis.call("get", KEYS[1]) == ARGV[1] then
                return redis.call("del", KEYS[1])
            else
                return 0
            end
        ';

        $result = $this->redis->eval($lua, [$this->resource, $this->token], 1);
        $this->token = null;
        return $result == 1;
    }
}

// Usage:
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);

$lock = new RedisLock($redis, 'order_processing_1042', 3000);

if ($lock->acquire()) {
    try {
        echo "Distributed lock acquired! Processing order...\n";
    } finally {
        $lock->release();
        echo "Distributed lock released.\n";
    }
} else {
    echo "Could not acquire lock; another worker is currently processing this order.\n";
}

5. Database Row-Level Locking (Pessimistic vs. Optimistic)

When coordinating database mutations across concurrent HTTP requests:

Pessimistic Locking (SELECT ... FOR UPDATE)

Blocks other transactions attempting to read with lock or update the selected row until the current transaction commits:

<?php

$pdo->beginTransaction();

try {
    // Acquire exclusive row lock
    $stmt = $pdo->prepare("SELECT balance FROM accounts WHERE id = :id FOR UPDATE");
    $stmt->execute(['id' => $accountId]);
    $balance = (float) $stmt->fetchColumn();

    if ($balance >= $withdrawAmount) {
        $newBalance = $balance - $withdrawAmount;
        $update = $pdo->prepare("UPDATE accounts SET balance = :balance WHERE id = :id");
        $update->execute(['balance' => $newBalance, 'id' => $accountId]);
        $pdo->commit();
    } else {
        $pdo->rollBack();
    }
} catch (Throwable $e) {
    $pdo->rollBack();
    throw $e;
}

Optimistic Locking (Version Field)

Avoids holding database locks by adding an integer version column to the table. Updates only succeed if the version in the database matches what was read:

<?php

$stmt = $pdo->prepare("SELECT id, balance, version FROM accounts WHERE id = :id");
$stmt->execute(['id' => $accountId]);
$account = $stmt->fetch(PDO::FETCH_ASSOC);

$update = $pdo->prepare("
    UPDATE accounts 
    SET balance = :balance, version = version + 1 
    WHERE id = :id AND version = :version
");
$update->execute([
    'balance' => $account['balance'] - $withdrawAmount,
    'id'      => $account['id'],
    'version' => $account['version']
]);

// execute() only returns true/false; rowCount() tells how many rows were updated
if ($update->rowCount() === 0) {
    // Conflict detected: another request modified the row in the meantime
    throw new RuntimeException("Concurrent update conflict. Please retry.");
}

Best Practices and Deadlock Prevention

  1. Always Use finally Blocks: Ensure locks and semaphores are reliably released even when exceptions or early returns occur.
  2. Set Sensible Timeouts: Always attach a TTL or timeout to locks to avoid deadlocks in case of unexpected worker crashes.
  3. Lock in a Uniform Order: When acquiring multiple locks, always acquire them in the exact same alphabetical or numerical sequence to avoid classic circular deadlocks (Dining Philosophers problem).

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents