定制 utopia-php/lock 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

utopia-php/lock

Composer 安装命令:

composer require utopia-php/lock

包简介

A simple lock library to coordinate access to shared resources across coroutines, processes and hosts

README 文档

README

Important

This repository is a read-only mirror of the utopia-php monorepo. Development happens in packages/lock — please open issues and pull requests there.

Build Status Total Downloads Discord

Utopia Lock library is a simple and lite library for coordinating access to shared resources in PHP applications. This library provides a single interface backed by four lock primitives — mutex, semaphore, file and distributed — for serialising work across coroutines, processes, hosts and clusters. This library is maintained by the Appwrite team.

Although this library is part of the Utopia Framework project it is dependency free and can be used as standalone with any other PHP project or framework.

Getting Started

Install using composer:

composer require utopia-php/lock

System Requirements

Utopia Lock requires PHP 8.3 or later. We recommend using the latest PHP version whenever possible.

The Mutex and Semaphore primitives require the Swoole extension (>=6.0). The Distributed primitive requires the Redis extension.

Features

Supported Primitives

Primitive Scope Backing Use when
Mutex Single worker, coroutine-scoped Swoole\Coroutine\Channel(1) Serialising access to an in-memory resource per worker
Semaphore Single worker, coroutine-scoped Swoole\Coroutine\Channel($permits) Capping concurrent access (e.g. outbound request pool)
File Single host, cross-process flock() Cron guards, shared-filesystem coordination
Distributed Cross-host, cluster-wide Redis SET NX EX + Lua release Coordinating workers across machines

Usage

The Interface

All primitives implement the same Utopia\Lock\Lock interface:

<?php

namespace Utopia\Lock;

interface Lock
{
    public function acquire(float $timeout = 0.0): bool;
    public function tryAcquire(): bool;
    public function release(): void;

    /** @template T; @param callable(): T $callback; @return T */
    public function withLock(callable $callback, float $timeout = 0.0): mixed;
}

withLock() throws Utopia\Lock\Exception\Contention if the lock cannot be acquired before the timeout expires.

Mutex

<?php

require_once __DIR__ . '/vendor/autoload.php';

use Swoole\Coroutine;
use Utopia\Lock\Mutex;
use function Swoole\Coroutine\run;

$mutex = new Mutex();

run(function () use ($mutex): void {
    for ($i = 0; $i < 8; $i++) {
        Coroutine::create(function () use ($mutex, $i): void {
            $mutex->withLock(function () use ($i): void {
                echo "worker {$i} holds the mutex\n";
                Coroutine::usleep(10_000);
            }, timeout: 5.0);
        });
    }
});

Semaphore

<?php

use Utopia\Lock\Semaphore;

$semaphore = new Semaphore(permits: 3);

$semaphore->withLock(function () {
    // at most three coroutines can be here at once
});

File

<?php

use Utopia\Lock\File;

$lock = new File('/var/run/my-daily-job.lock');

if (! $lock->tryAcquire()) {
    exit("another copy is already running\n");
}

try {
    runDailyJob();
} finally {
    $lock->release();
}

Pass LOCK_SH for shared (reader) mode:

$readers = new File('/tmp/cache.lock', LOCK_SH);
$readers->withLock(fn () => readCache(), timeout: 1.0);

Distributed

<?php

use Redis;
use Utopia\Lock\Distributed;

$redis = new Redis();
$redis->connect('redis.internal', 6379);

$lock = new Distributed($redis, key: 'jobs:rebuild-index', ttl: 120);

$lock->setLogger(fn (string $message) => \error_log($message));

$lock->withLock(function () {
    rebuildSearchIndex();
}, timeout: 30.0);

Release is atomic: a Lua script verifies the lock value still matches this instance's token before deleting, so a lock that expires and is re-acquired elsewhere is never released by accident.

Exception Handling

<?php

use Utopia\Lock\Exception;
use Utopia\Lock\Exception\Contention as ContentionException;

try {
    $lock->withLock($work, timeout: 5.0);
} catch (ContentionException) {
    // timed out trying to acquire
} catch (Exception) {
    // base class, catches anything thrown by this package
}

Tests

To run all unit tests, use the following Docker command:

docker compose exec tests vendor/bin/phpunit --configuration phpunit.xml tests

To run static code analysis, use the following PHPStan command:

docker compose exec tests vendor/bin/phpstan analyse --memory-limit=512M

Security

We take security seriously. If you discover any security-related issues, please email security@appwrite.io instead of using the issue tracker.

Contributing

All code contributions - including those of people having commit access - must go through a pull request and be approved by a core developer before being merged. This is to ensure a proper review of all the code.

We truly ❤️ pull requests! If you wish to help, you can learn more about how you can contribute to this project in the contribution guide.

Copyright and license

The MIT License (MIT) http://www.opensource.org/licenses/mit-license.php

utopia-php/lock 适用场景与选型建议

utopia-php/lock 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 27.29k 次下载、GitHub Stars 达 1, 最近一次更新时间为 2026 年 05 月 15 日, 在 PHP 生态内属于活跃度较高的组件。

我们在过去多个企业项目中使用过 utopia-php/lock 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 utopia-php/lock 我们能提供哪些服务?
定制开发 / 二次开发

基于 utopia-php/lock 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 27.29k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 1
  • 点击次数: 39
  • 依赖项目数: 2
  • 推荐数: 0

GitHub 信息

  • Stars: 1
  • Watchers: 0
  • Forks: 1
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2026-05-15