mirror of
https://github.com/danog/file.git
synced 2024-12-02 09:17:57 +01:00
Release mutex if process is killed
This commit is contained in:
parent
4dd0879884
commit
c37be07347
@ -4,7 +4,6 @@ namespace Amp\File;
|
|||||||
|
|
||||||
use Amp\Sync\Lock;
|
use Amp\Sync\Lock;
|
||||||
use Amp\Sync\Mutex;
|
use Amp\Sync\Mutex;
|
||||||
use Amp\Sync\SyncException;
|
|
||||||
use function Amp\delay;
|
use function Amp\delay;
|
||||||
|
|
||||||
final class FileMutex implements Mutex
|
final class FileMutex implements Mutex
|
||||||
@ -20,39 +19,16 @@ final class FileMutex implements Mutex
|
|||||||
|
|
||||||
public function acquire(): Lock
|
public function acquire(): Lock
|
||||||
{
|
{
|
||||||
// Try to create the lock file. If the file already exists, someone else
|
$f = \fopen($this->fileName, 'c');
|
||||||
// has the lock, so set an asynchronous timer and try again.
|
|
||||||
while (true) {
|
while (true) {
|
||||||
try {
|
if (\flock($f, LOCK_EX|LOCK_NB)) {
|
||||||
$file = openFile($this->fileName, 'x');
|
|
||||||
|
|
||||||
// Return a lock object that can be used to release the lock on the mutex.
|
// Return a lock object that can be used to release the lock on the mutex.
|
||||||
$lock = new Lock($this->release(...));
|
$lock = new Lock(fn () => \flock($f, LOCK_UN));
|
||||||
|
|
||||||
$file->close();
|
|
||||||
|
|
||||||
return $lock;
|
return $lock;
|
||||||
} catch (FilesystemException) {
|
|
||||||
delay(self::LATENCY_TIMEOUT);
|
|
||||||
}
|
}
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
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
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user