1. Go to this page and download the library: Download utopia-php/lock library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
utopia-php / lock example snippets
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;
}
woole\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);
});
}
});
use Utopia\Lock\Semaphore;
$semaphore = new Semaphore(permits: 3);
$semaphore->withLock(function () {
// at most three coroutines can be here at once
});
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();
}
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);
$token = $lock->token();
if ($token === null) {
throw new RuntimeException('The lock is not held');
}
$refresher = (new Distributed($otherRedis, key: 'jobs:rebuild-index', ttl: 120))
->adopt($token);
$refresher->refresh();
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
}
bash
composer
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.