3 // Provide some ability to lock a PHP function so that multiple processes
4 // can't run the function concurrently
5 if(! function_exists('lock_function')) {
6 function lock_function($fn_name, $block = true, $wait_sec = 2, $timeout = 30) {
8 $wait_sec = 2; // don't let the user pick a value that's likely to crash the system
14 q("LOCK TABLE `locks` WRITE");
15 $r = q("SELECT `locked`, `created` FROM `locks` WHERE `name` = '%s' LIMIT 1",
19 if((count($r)) AND (!$r[0]['locked'] OR (strtotime($r[0]['created']) < time() - 3600))) {
20 q("UPDATE `locks` SET `locked` = 1, `created` = '%s' WHERE `name` = '%s'",
21 dbesc(datetime_convert()),
26 elseif(! $r) { // the Boolean value for count($r) should be equivalent to the Boolean value of $r
27 q("INSERT INTO `locks` (`name`, `created`, `locked`) VALUES ('%s', '%s', 1)",
29 dbesc(datetime_convert())
36 if(($block) && (! $got_lock))
39 } while(($block) && (! $got_lock) && ((time() - $start) < $timeout));
41 logger('lock_function: function ' . $fn_name . ' with blocking = ' . $block . ' got_lock = ' . $got_lock . ' time = ' . (time() - $start), LOGGER_DEBUG);
47 if(! function_exists('block_on_function_lock')) {
48 function block_on_function_lock($fn_name, $wait_sec = 2, $timeout = 30) {
50 $wait_sec = 2; // don't let the user pick a value that's likely to crash the system
55 $r = q("SELECT locked FROM locks WHERE name = '%s' LIMIT 1",
59 if(count($r) && $r[0]['locked'])
62 } while(count($r) && $r[0]['locked'] && ((time() - $start) < $timeout));
68 if(! function_exists('unlock_function')) {
69 function unlock_function($fn_name) {
70 $r = q("UPDATE `locks` SET `locked` = 0, `created` = '0000-00-00 00:00:00' WHERE `name` = '%s'",
74 logger('unlock_function: released lock for function ' . $fn_name, LOGGER_DEBUG);