-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
850da66
commit c084edf
Showing
2 changed files
with
68 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,45 @@ | ||
<?php | ||
|
||
namespace Talmp\Phputils; | ||
|
||
# This is an mutex implementation at OS level | ||
class Mutex | ||
{ | ||
public readonly string $lock_name; | ||
|
||
public function __construct(string $lock_name) | ||
{ | ||
$this->lock_name = $lock_name; | ||
} | ||
|
||
public function lock( | ||
float $timeout = INF /* microseconds */ | ||
): bool { | ||
$timepass = 0; | ||
|
||
while ($timepass <= $timeout) { | ||
$mkdir = @mkdir("/dev/shm/{$this->lock_name}"); | ||
|
||
if ($mkdir) { | ||
return true; | ||
} | ||
|
||
$timepass += 100000; | ||
|
||
usleep(100000); // check every 0.1s | ||
} | ||
|
||
// throw exception here because lock was expected to success | ||
// client api should not have to check and handle this | ||
throw new \Exception('PU2991: unable to get lock'); | ||
} | ||
|
||
public function unlock(): void | ||
{ | ||
$rmdir = rmdir("/dev/shm/{$this->lock_name}"); | ||
|
||
if (! $rmdir) { | ||
throw new \Exception('PU2992: unable unlock'); | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,23 @@ | ||
<?php | ||
|
||
use PHPUnit\Framework\TestCase; | ||
use Talmp\Phputils\Mutex; | ||
|
||
class MutexTest extends TestCase | ||
{ | ||
public function test_lock_unlock(): void | ||
{ | ||
$lock_name = bin2hex(random_bytes(16)); | ||
|
||
$this->assertFalse(file_exists('/dev/shm/'.$lock_name)); | ||
|
||
$mutex = new Mutex($lock_name); | ||
$mutex->lock(0); | ||
|
||
$this->assertTrue(file_exists('/dev/shm/'.$lock_name)); | ||
|
||
$mutex->unlock(); | ||
|
||
$this->assertFalse(file_exists('/dev/shm/'.$lock_name)); | ||
} | ||
} |