3 namespace Friendica\Util;
6 * @file src/Util/Lock.php
7 * @brief Functions for preventing parallel execution of functions
15 * @brief This class contain Functions for preventing parallel execution of functions
20 * @brief Sets a lock for a given name
22 * @param string $fn_name Name of the lock
23 * @param integer $timeout Seconds until we give up
24 * @param integer $wait_sec Time between to lock attempts
26 * @return boolean Was the lock successful?
28 public static function set($fn_name, $timeout = 30, $wait_sec = 2) {
38 $lock = dba::select('locks', array('locked', 'pid'), array('name' => $fn_name), array('limit' => 1));
40 if (dbm::is_result($lock)) {
41 if ($lock['locked']) {
42 // When the process id isn't used anymore, we can safely claim the lock for us.
43 if (!posix_kill($lock['pid'], 0)) {
44 $lock['locked'] = false;
46 // We want to lock something that was already locked by us? So we got the lock.
47 if ($lock['pid'] == getmypid()) {
51 if (!$lock['locked']) {
52 dba::update('locks', array('locked' => true, 'pid' => getmypid()), array('name' => $fn_name));
55 } elseif (!dbm::is_result($lock)) {
56 dba::insert('locks', array('name' => $fn_name, 'locked' => true, 'pid' => getmypid()));
65 } while (!$got_lock AND ((time() - $start) < $timeout));
71 * @brief Removes a lock if it was set by us
73 * @param string $fn_name Name of the lock
75 public static function remove($fn_name) {
76 dba::update('locks', array('locked' => false, 'pid' => 0), array('name' => $fn_name, 'pid' => getmypid()));