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((dbm::is_result($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 (! dbm::is_result($r)) {
27 /// @TODO the Boolean value for count($r) should be equivalent to the Boolean value of $r
28 q("INSERT INTO `locks` (`name`, `created`, `locked`) VALUES ('%s', '%s', 1)",
30 dbesc(datetime_convert())
37 if(($block) && (! $got_lock))
40 } while(($block) && (! $got_lock) && ((time() - $start) < $timeout));
42 logger('lock_function: function ' . $fn_name . ' with blocking = ' . $block . ' got_lock = ' . $got_lock . ' time = ' . (time() - $start), LOGGER_DEBUG);
48 if(! function_exists('block_on_function_lock')) {
49 function block_on_function_lock($fn_name, $wait_sec = 2, $timeout = 30) {
51 $wait_sec = 2; // don't let the user pick a value that's likely to crash the system
56 $r = q("SELECT locked FROM locks WHERE name = '%s' LIMIT 1",
60 if (dbm::is_result($r) && $r[0]['locked'])
63 } while(dbm::is_result($r) && $r[0]['locked'] && ((time() - $start) < $timeout));
69 if(! function_exists('unlock_function')) {
70 function unlock_function($fn_name) {
71 $r = q("UPDATE `locks` SET `locked` = 0, `created` = '0000-00-00 00:00:00' WHERE `name` = '%s'",
75 logger('unlock_function: released lock for function ' . $fn_name, LOGGER_DEBUG);