0

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.

  1. I read the value in the file, increment, and write the new value at the beginning
  2. Do my stuff
  3. 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!!

B 7
  • 670
  • 7
  • 23
  • given you say the script only runs for 1s, are you **SURE** you've got 2+ instances of that script in the same 1 second interval? Put some `sleep()` calls in there to broaden the interval to make sure you really are getting a "collision". – Marc B Aug 16 '16 at 16:37
  • I would access the OS instead of trying to get PHP to tell me. Just use a shell exec and parse the running threads http://stackoverflow.com/questions/268680/how-can-i-monitor-the-active-thread-count-of-a-process-jvm-on-linux – Wes Aug 16 '16 at 16:41
  • @MarcB I tried with a `sleep(15);` before I post this question, just to be sure...I will edit the question – B 7 Aug 17 '16 at 07:35
  • @Wes I wanted to do that, but the OS only give the number of active threads php-fpm, and I can't know which script it is. I have some other scripts on this server and I want to limit only this one – B 7 Aug 17 '16 at 07:39
  • Perhaps you should store your active instances in an APC (application variable). Add and remove array entries when you start and end your script. You don't need a file to do this and adding and removing entries from a variable will be much easier than using a text file. - A db table would allow you to log whats happening. I would not recommend using text files for persistent storage. – Wes Aug 19 '16 at 16:48

0 Answers0