]> git.mxchange.org Git - friendica.git/blob - src/Util/Lock.php
03e8545adfdaadc20866268ce7b8c1156648955c
[friendica.git] / src / Util / Lock.php
1 <?php
2
3 namespace Friendica\Util;
4
5 /**
6  * @file src/Util/Lock.php
7  * @brief Functions for preventing parallel execution of functions
8  *
9  */
10
11 use dba;
12 use dbm;
13
14 /**
15  * @brief This class contain Functions for preventing parallel execution of functions
16  */
17 class Lock {
18
19
20 // Provide some ability to lock a PHP function so that multiple processes
21 // can't run the function concurrently
22
23         public static function set($fn_name, $wait_sec = 2, $timeout = 30) {
24                 if ($wait_sec == 0) {
25                         $wait_sec = 2;
26                 }
27
28                 $got_lock = false;
29                 $start = time();
30
31                 do {
32                         dba:p("LOCK TABLE `locks` WRITE");
33                         $lock = dba::select('locks', array('locked'), array('name' => $fn_name), array('limit' => 1));
34
35                         if ((dbm::is_result($lock)) AND !$lock['locked']) {
36                                 dba::update('locks', array('locked' => true), array('name' => $fn_name));
37                                 $got_lock = true;
38                         } elseif (!dbm::is_result($lock)) {
39                                 dbm::insert('locks', array('name' => $fn_name, 'locked' => true));
40                                 $got_lock = true;
41                         }
42
43                         dbm::p("UNLOCK TABLES");
44
45                         if (!$got_lock) {
46                                 sleep($wait_sec);
47                         }
48                 } while (!$got_lock AND ((time() - $start) < $timeout));
49
50                 logger('lock_function: function ' . $fn_name . ' with blocking = ' . $block . ' got_lock = ' . $got_lock . ' time = ' . (time() - $start), LOGGER_DEBUG);
51
52                 return $got_lock;
53         }
54
55         public static function remove($fn_name) {
56                 dba::update('locks', array('locked' => false), array('name' => $fn_name));
57
58                 logger('unlock_function: released lock for function ' . $fn_name, LOGGER_DEBUG);
59
60                 return;
61         }
62 }