Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add variant of mutex based on flock #80

Open
wants to merge 6 commits into
base: 3.x
Choose a base branch
from
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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');
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why not touch here?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a one-time cost, not really worth adding a touch here imo

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));
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This will block for a short duration, no?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I considered adding a variant that used parallel but decided that the overhead to communicate to/from the IPC worker will be way worse than that of a single syscall that returns immediately.


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);
}
}
}
Loading