I have a PHP script that runs during about 1s (15s for my tests), and I would like to store the number of threads that are running this script to do a specific action when too many scripts/threads are running.
To do that I tried to store the number of opened tasks in a file.
- I read the value in the file, increment, and write the new value at the beginning
- Do my stuff
- Read the value in the file, decrement, and write the new value at the beginning
Here is my code:
<?php
define("MAX_THREADS", 5);
define("LOCK_FILE", "threads.txt");
$fp = fopen(LOCK_FILE, "r+");
if (flock($fp, LOCK_EX)) { // acquire an exclusive lock
$threadNb = fread($fp, filesize(LOCK_FILE));
/*
* if $threadNb > MAX_THREAD => Do something
*/
ftruncate($fp, 0); // truncate file
fwrite($fp, ++$threadNb);
fflush($fp); // flush output before releasing the lock
flock($fp, LOCK_UN); // release the lock
} else {
echo "Failed lock the file!";
}
fclose($fp);
// Do stuff
// ...
// End of script
sleep(15);
$fp = fopen(LOCK_FILE, "r+");
if (flock($fp, LOCK_EX)) { // acquire an exclusive lock
$threadNb = fread($fp, filesize(LOCK_FILE));
ftruncate($fp, 0); // truncate file
fwrite($fp, --$threadNb);
fflush($fp); // flush output before releasing the lock
flock($fp, LOCK_UN); // release the lock
} else {
echo "Failed lock the file!";
}
fclose($fp);
PROBLEM: The value of $threadNb
is always equal to 0!!