sof3/rwlock

PHP 的独占和读写锁

0.1.1 2022-03-05 13:06 UTC

This package is auto-updated.

Last update: 2024-09-28 03:25:34 UTC


README

PHP 的独占和读写锁。

这是将我的 JavaScript 库 rwlock-promise 快速移植到 PHP 中的一个版本。由于这个原因,某些部分可能不太符合惯例。

此库使用 await-generator 框架来公开异步函数调用 API。

用法

$mutex = new Mutex;

$epoch = time();

yield $mutex->run(function() use($epoch) {
	echo "Start 1: ", time() - $epoch, "\n";
	yield $this->waitSeconds(2);
	echo "End 1: ", time() - $epoch, "\n";
});

yield $mutex->run(function() use($epoch) {
	echo "Start 2: ", time() - $epoch, "\n";
	yield $this->waitSeconds(1);
	echo "End 2: ", time() - $epoch, "\n";
});

上面的代码应该输出

Start 1: 0
End 1: 2
Start 2: 2
End 2: 3

第二个生成器只有在第一个生成器返回后才会运行。

$mutex = new RwLock;

$epoch = time();

Await::g2c($mutex->readClosure(function() use($epoch) {
	echo "Start 1: ", time() - $epoch, "\n";
	yield $this->waitSeconds(2);
	echo "End 1: ", time() - $epoch, "\n";
}));

Await::g2c($mutex->readClosure(function() use($epoch, $mutex) {
	echo "Start 2: ", time() - $epoch, "\n";
	yield $this->waitSeconds(1);
	echo "End 2: ", time() - $epoch, "\n";

	Await::g2c($mutex->readClosure(function() use($epoch) {
		echo "Start 3: ", time() - $epoch, "\n";
		yield $this->waitSeconds(2);
		echo "End 3: ", time() - $epoch, "\n";
	}));

	Await::f2c($mutex->writeClosure(function() use($epoch) {
		echo "Start 4: ", time() - $epoch, "\n";
		yield $this->waitSeconds(2);
		echo "End 4: ", time() - $epoch, "\n";
	}));

	Await::f2c($mutex->readClosure(function() use($epoch) {
		echo "Start 5: ", time() - $epoch, "\n";
		yield $this->waitSeconds(2);
		echo "End 5: ", time() - $epoch, "\n";
	}));
}));

上面的代码应该输出

Start 1: 0
Start 2: 0
End 2: 1
Start 3: 1
End 1: 2
End 3: 3
Start 4: 3
End 4: 5
Start 5: 5
End 5: 7

在读写块内部 yield(等待)读写是没有意义的;特别是,在读写块内部产生另一个写操作会导致死锁。如上所示,使用 Await::g2c 来安排读写操作,而不在它上阻塞。然而,你总是必须使用 yieldf2c/g2c 进行读写,因为它只返回一个生成器,如果你不对它调用任何操作,它什么也不做。