OpenSwoole\Lock::__construct

Latest version: pecl install openswoole-22.1.2 | composer require openswoole/core:22.1.5

Declaration

<?php OpenSwoole\\Lock::__construct ( [ int $type [, string $file_lock_location ] )

Parameters

type

The type of lock OpenSwoole\Constant::FILELOCK, OpenSwoole\Constant::RWLOCK, OpenSwoole\Constant::SEM, OpenSwoole\Constant::MUTEX, OpenSwoole\Constant::SPINLOCK

file_lock_location

The locaiton of the lock file, for example: /tmp/file.lock

Return

Description

Create a lock for process sync.

Lock types:

OpenSwoole\Constant::FILELOCKfile lock
OpenSwoole\Constant::RWLOCKread write lock
OpenSwoole\Constant::SEMLinux semaphore
OpenSwoole\Constant::MUTEXMutex
OpenSwoole\Constant::SPINLOCKspin lock

Example

<?php

$lock = new OpenSwoole\Lock(OpenSwoole\Constant::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";
Last updated on September 20, 2022