PHP code example of denismitr / mutex

1. Go to this page and download the library: Download denismitr/mutex library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

denismitr / mutex example snippets


$lock = MutexFactory::fileLock(__FILE__); // or some other file name like /tmp/some-id

$lock = MutexFactory::semaphoreLock(__FILE__); // or some other file name like /tmp/some-id

$this->redis = new Client([
    'host' => 'localhost',
    'port' => 6379,
    'database' => 0,
]);

$this->lock = MutexFactory::pRedisLock($this->redis, "some-key", 20);

$lock->acquire();

// Do some critical stuff here

$lock->release();

$lock->safe(function() {
    // Lock will be acuqired and released automatically
    
    // Do some critical stuff safely
});

$lock->try(function() use ($room, $from, $to) {
    // e.g
    return $room->isFree($from, $to);
})->then(function() use ($room, $from, $to) {
    // e.g.
    // Lock is aquired automatically
    
    $room->book($from, $to);
})->fail(function() use ($user) {
    // this callback will fire if the condition in try closure fails
    // e.g.
    $user->notify("Room is not available for requested time period.");
});

$lock->loop($timeoutInSeconds, function($loop, $i) ($user, $ads) {
    // lock is acquired and released automatically when loop is done
    // e.g. send out only 10 ads to user friends
    
    // Laravel collections example
    $user->friends->each->notify($adds->random());
    
    if ($i >= 10) {
        $loop->stop();
    }
});