Hi all!
I've made this question: http://stackoverflow.com/questions/2921469/php-mutual-exclusion-mutex
As said there, I want several sources to send their stats once in a while, and these stats will be showed at the website's main page.
My problem is that I want this to be done in an atomic manner, so no update of the stats will overlap another one running in the background.
Now, I came up with this solution and I want you PHP experts to judge it.
stats.php
<?php
define("my_counter", 12);
?>
index.php
<?php
include "stats.php";
echo constant("my_counter");
?>
update.php
<?php
$old_error_reporting = error_reporting(0);
include "stats.php";
define("my_stats_template",'
<?php
define("my_counter", %d);
?>
');
$fd = fopen("stats.php", "w+");
if($fd)
{
if (flock($fd, LOCK_EX))
{
$my_counter = 0;
try
{
$my_counter = constant("my_counter");
}
catch(Exception $e) { }
$my_counter++;
$new_stats = sprintf(constant("my_stats_template"), $my_counter);
echo "Counter should stand at $my_counter";
fwrite($fd, $new_stats);
}
flock($fd, LOCK_UN);
fclose($fd);
}
error_reporting($old_error_reporting);
?>
Several clients will call the "update.php" file once every 60sec each.
The "index.php" is going to use the "stats.php" file all the time as you can see.
What's your opinion?