note 72600 added to ref.sem
| From: | mr dot smaon at gmail dot com | Date: | Thu, 25 Jan 2007 17:08:38 +0000 |
| Subject: | note 72600 added to ref.sem | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-122197@lists.php.net to get a copy of this message | ||
Here is a simple Mutex class implementation, using semaphore on Linux and flock on windows.
Filename is optionnal, but you can provide it anyway. This way the file will be created on windows,
not on linux as it is not needed.
It's fast written and certainly lacks error checking code.
<?php
class Mutex
{
private $id;
private $sem_id;
private $is_acquired = false;
private $is_windows = false;
private $filename = '';
private $filepointer;
function __construct()
{
if(substr(PHP_OS, 0, 3) == 'WIN')
$this->is_windows = true;
}
public function init($id, $filename = '')
{
$this->id = $id;
if($this->is_windows)
{
if(empty($filename)){
print "no filename specified";
return false;
}
else
$this->filename = $filename;
}
else
{
if(!($this->sem_id = sem_get($this->id, 1))){
print "Error getting semaphore";
return false;
}
}
return true;
}
public function acquire()
{
if($this->is_windows)
{
if(($this->filepointer = @fopen($this->filename, "w+")) == false)
{
print "error opening mutex file<br>";
return false;
}
if(flock($this->filepointer, LOCK_EX) == false)
{
print "error locking mutex file<br>";
return false;
}
}
else
{
if (! sem_acquire($this->sem_id)){
print "error acquiring semaphore";
return false;
}
}
$this->is_acquired = true;
return true;
}
public function release()
{
if(!$this->is_acquired)
return true;
if($this->is_windows)
{
if(flock($this->filepointer, LOCK_UN) == false)
{
print "error unlocking mutex file<br>";
return false;
}
fclose($this->filepointer);
}
else
{
if (! sem_release($this->sem_id)){
print "error releasing semaphore";
return false;
}
}
$this->is_acquired = false;
return true;
}
public function getId()
{
return $this->sem_id;
}
}
?>
Example use:
<?php
$mutex = new Mutex();
$mutex->init(1, "mutex_file.txt");
$mutex->acquire();
//Whatever you want single-threaded here...
$mutex->release();
?>
----
Server IP: 194.153.94.10
Probable Submitter: 84.16.71.2
----
Manual Page -- http://www.php.net/manual/en/ref.sem.php
Edit -- https://master.php.net/note/edit/72600
Del: integrated -- https://master.php.net/note/delete/72600/integrated
Del: useless -- https://master.php.net/note/delete/72600/useless
Del: bad code -- https://master.php.net/note/delete/72600/bad+code
Del: spam -- https://master.php.net/note/delete/72600/spam
Del: non-english -- https://master.php.net/note/delete/72600/non-english
Del: in docs -- https://master.php.net/note/delete/72600/in+docs
Del: other reasons-- https://master.php.net/note/delete/72600
Reject -- https://master.php.net/note/reject/72600
Search -- https://master.php.net/manage/user-notes.php