Skip to content

Commit

Permalink
Improve Lock::block() method
Browse files Browse the repository at this point in the history
  • Loading branch information
huangdijia committed Aug 6, 2024
1 parent c305035 commit ccfdee6
Showing 1 changed file with 8 additions and 3 deletions.
11 changes: 8 additions & 3 deletions src/lock/src/Driver/AbstractLock.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@
use Hyperf\Support\Traits\InteractsWithTime;
use Override;

use function Hyperf\Support\now;

abstract class AbstractLock implements LockInterface
{
use InteractsWithTime;
Expand Down Expand Up @@ -76,14 +78,17 @@ public function get(?callable $callback = null)
#[Override]
public function block(int $seconds, ?callable $callback = null)
{
$starting = $this->currentTime();
$starting = ((int) now()->format('Uu')) / 1000;
$milliseconds = $seconds * 1000;

while (! $this->acquire()) {
usleep($this->sleepMilliseconds * 1000);
$now = ((int) now()->format('Uu')) / 1000;

if ($this->currentTime() - $seconds >= $starting) {
if (($now + $this->sleepMilliseconds - $milliseconds) >= $starting) {
throw new LockTimeoutException();
}

usleep($this->sleepMilliseconds * 1000);
}

if (is_callable($callback)) {
Expand Down

0 comments on commit ccfdee6

Please sign in to comment.