note 92731 added to function.flock

From: Date: Thu, 06 Aug 2009 11:31:10 +0000
Subject: note 92731 added to function.flock
Groups: php.notes 
Request: Send a blank email to php-notes+get-159145@lists.php.net to get a copy of this message
I use exclusive writing to replace standard flock(): <?php // get/set lock file name function m_lock_file( $format = null ) { static $file_format = './%s.lock'; if ($format !== null) { $file_format = $format; } return $file_format; } // acquire/check/release lock function m_lock( $lockId, $acquire = null ) { static $handlers = array(); if (is_bool($acquire)) { $file = sprintf(m_lock_file(), md5($lockId), $lockId); } if ($acquire === false) { if (isset($handlers[$lockId])) { @fclose($handlers[$lockId]); @unlink($file); unset($handlers[$lockId]); } else { trigger_error("Lock '$lockId' is already unlocked", E_USER_WARNING); } } if ($acquire === true) { if (!isset($handlers[$lockId])) { $handler = false; $count = 100; do { if (!file_exists($file) || @unlink($file)) { $handler = @fopen($file, "x"); } if (false === $handler) { usleep(10000); } else { $handlers[$lockId] = $handler; } } while (false === $handler && $count-- > 0); } else { trigger_error("Lock '$lockId' is already locked", E_USER_WARNING); } } return isset($handlers[$lockId]); } ?> Usage sample: <?php $lockId = "qq"; m_lock($lockId, true); if (m_lock($lockId)) { echo "locked"; // here you can perform any thread-safe operations usleep(300 * 1000); m_lock($lockId, false); } else { echo "not locked"; } ?> ---- Server IP: 78.41.111.4 Probable Submitter: 91.142.81.27 ---- Manual Page -- http://www.php.net/manual/en/function.flock.php Edit -- https://master.php.net/note/edit/92731 Del: integrated -- https://master.php.net/note/delete/92731/integrated Del: useless -- https://master.php.net/note/delete/92731/useless Del: bad code -- https://master.php.net/note/delete/92731/bad+code Del: spam -- https://master.php.net/note/delete/92731/spam Del: non-english -- https://master.php.net/note/delete/92731/non-english Del: in docs -- https://master.php.net/note/delete/92731/in+docs Del: other reasons-- https://master.php.net/note/delete/92731 Reject -- https://master.php.net/note/reject/92731 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#159145) next »