- Lock
- 示例:
- 示例:
Lock
1.6.4
版本增加了锁的实现。PHP
代码中可以很方便地创建一个锁,用来实现数据同步。Lock
类支持5
种锁的类型:
- 文件锁
SWOOLE_FILELOCK
- 读写锁
SWOOLE_RWLOCK
- 信号量
SWOOLE_SEM
- 互斥锁
SWOOLE_MUTEX
- 自旋锁
SWOOLE_SPINLOCK
注意:请勿在onReceive
等回调函数中创建锁,否则底层的GlobalMemory
内存会持续增长,造成内存泄漏。
示例:
$lock = new swoole_lock(SWOOLE_MUTEX);
echo "[Master]create lock\n";
$lock->lock();
if (pcntl_fork() > 0)
{
sleep(1);
$lock->unlock();
}
else
{
echo "[Child] Wait Lock\n";
$lock->lock();
echo "[Child] Get Lock\n";
$lock->unlock();
exit("[Child] exit\n");
}
echo "[Master]release lock\n";
unset($lock);
sleep(1);
echo "[Master]exit\n";