PHP code example of gaillard / mongo-lock
1. Go to this page and download the library: Download gaillard/mongo-lock 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/ */
gaillard / mongo-lock example snippets
$writer = function($value) {
$db = (new \MongoClient())->selectDB('locksExample');
$data = $db->selectCollection('data');
$locker = new Locker($db->selectCollection('locks'), 0);
while (true) {
$locker->writeLock('theId', 1000);
$data->update(['_id' => 1], ['_id' => 1, 'key' => $value], ['upsert' => true]);
$data->update(['_id' => 2], ['_id' => 2, 'key' => $value], ['upsert' => true]);
$data->update(['_id' => 3], ['_id' => 3, 'key' => $value], ['upsert' => true]);
$data->update(['_id' => 4], ['_id' => 4, 'key' => $value], ['upsert' => true]);
$locker->writeUnlock('theId');
}
};
$reader = function() {
$db = (new \MongoClient())->selectDB('locksExample');
$data = $db->selectCollection('data');
$locker = new Locker($db->selectCollection('locks'), 100000);
while (true) {
$readerId = $locker->readLock('theId', 1000);
foreach ($data->find()->sort(['_id' => 1]) as $doc) {
echo "{$doc['key']} ";
}
echo "\n";
$locker->readUnlock('theId', $readerId);
usleep(100000);
}
};
$writerOnePid = pcntl_fork();
if ($writerOnePid === 0) {
$writer('pie');
exit;
}
$writerTwoPid = pcntl_fork();
if ($writerTwoPid === 0) {
$writer('cake');
exit;
}
$readerOnePid = pcntl_fork();
if ($readerOnePid === 0) {
$reader();
exit;
}
$readerTwoPid = pcntl_fork();
if ($readerTwoPid === 0) {
$reader();
exit;
}
sleep(4);
posix_kill($writerOnePid, SIGTERM);
posix_kill($writerTwoPid, SIGTERM);
posix_kill($readerOnePid, SIGTERM);
posix_kill($readerTwoPid, SIGTERM);
sh
./build.php