Skip to content

Instantly share code, notes, and snippets.

@nikunjkotecha
Created December 12, 2018 15:59
Show Gist options
  • Save nikunjkotecha/2beeb8b19fbca8007d2f7bb38a0e287c to your computer and use it in GitHub Desktop.
Save nikunjkotecha/2beeb8b19fbca8007d2f7bb38a0e287c to your computer and use it in GitHub Desktop.
<?php
/** ====================================================================== */
// Create table if not available.
db_query("CREATE TABLE IF NOT EXISTS {lock_test} (
id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
random_id int,
request_time varchar(50),
first_request_time varchar(50)
);")->execute();
/** ====================================================================== */
// Ensure we start in both requests at same time.
do {
$time = time();
} while ($time % 100 != 0);
print 'start time: ' . $time . PHP_EOL . PHP_EOL;
/** ====================================================================== */
$i = 0;
$connection = \Drupal::database();
$lock = new \Drupal\Core\Lock\DatabaseLockBackend($connection);
for ($i = 1; $i < 1000; $i++) {
process($i, $lock);
print 'Processed id: ' . $i . PHP_EOL;
}
function process($id, $lock) {
$time = microtime(TRUE);
$lock_key = 'lock_test_' . $id;
// Acquire lock to ensure parallel processes are executed one by one.
do {
$lock_acquired = $lock->acquire($lock_key);
// Sleep for half a second before trying again.
if (!$lock_acquired) {
usleep(500000);
}
} while (!$lock_acquired);
$result = db_query('select id from {lock_test} where random_id = :id', [
':id' => $id,
])->fetch();
if ($result) {
db_update('lock_test')
->fields(['request_time' => $time])
->condition('id', $result->id)
->execute();
}
else {
db_insert('lock_test')->fields(
[
'random_id' => $id,
'request_time' => $time,
'first_request_time' => $time,
]
)->execute();
}
sleep(3);
$lock->release($lock_key);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment