initial 2.0.0-a4 commit

This commit is contained in:
jerry
2020-11-03 21:02:24 +08:00
parent da584e0542
commit 29fa9d8662
48 changed files with 794 additions and 1470 deletions

View File

@@ -0,0 +1,44 @@
<?php
namespace ZM\Store\Lock;
use Swoole\Coroutine;
use Swoole\Coroutine\System;
use Swoole\Table;
class SpinLock
{
/** @var null|Table */
private static $kv_lock = null;
private static $delay = 1;
public static function init($key_cnt, $delay = 1)
{
self::$kv_lock = new Table($key_cnt, 0.7);
self::$delay = $delay;
self::$kv_lock->column('lock_num', Table::TYPE_INT, 8);
return self::$kv_lock->create();
}
public static function lock(string $key)
{
while (($r = self::$kv_lock->incr($key, 'lock_num')) > 1) { //此资源已经被锁上了
if(Coroutine::getCid() != -1) System::sleep(self::$delay / 1000);
else usleep(self::$delay * 1000);
}
}
public static function tryLock(string $key) {
if (($r = self::$kv_lock->incr($key, 'lock_num')) > 1) {
return false;
}
return true;
}
public static function unlock(string $key) {
return self::$kv_lock->set($key, ['lock_num' => 0]);
}
}