Skip to content

Commit

Permalink
Release mutex if process is killed
Browse files Browse the repository at this point in the history
  • Loading branch information
danog committed Dec 9, 2023
1 parent 4dd0879 commit c37be07
Showing 1 changed file with 4 additions and 28 deletions.
32 changes: 4 additions & 28 deletions src/FileMutex.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@

use Amp\Sync\Lock;
use Amp\Sync\Mutex;
use Amp\Sync\SyncException;
use function Amp\delay;

final class FileMutex implements Mutex
Expand All @@ -20,39 +19,16 @@ public function __construct(private readonly string $fileName)

public function acquire(): Lock
{
// Try to create the lock file. If the file already exists, someone else
// has the lock, so set an asynchronous timer and try again.
$f = \fopen($this->fileName, 'c');
while (true) {
try {
$file = openFile($this->fileName, 'x');

if (\flock($f, LOCK_EX|LOCK_NB)) {
// Return a lock object that can be used to release the lock on the mutex.
$lock = new Lock($this->release(...));

$file->close();
$lock = new Lock(fn () => \flock($f, LOCK_UN));

return $lock;
} catch (FilesystemException) {
delay(self::LATENCY_TIMEOUT);
}
}
}

/**
* Releases the lock on the mutex.
*
* @throws SyncException
*/
private function release(): void
{
try {
deleteFile($this->fileName);
} catch (\Throwable $exception) {
throw new SyncException(
'Failed to unlock the mutex file: ' . $this->fileName,
0,
$exception
);
delay(self::LATENCY_TIMEOUT);
}
}
}

0 comments on commit c37be07

Please sign in to comment.