phpconcurrency

PHP: how can I call a function in a non-blocking fashion?


I saw a couple of other question on the issue but not a clear answer.

I've a PHP file (must be PHP, cannot cron or other stuff) running from CLI where I must call the same function multiple time with different arguments:

doWork($param1);

doWork($param2);

doWork($param2);

function doWork($data)
{
//do stuff, write result to db
}

Each call makes HTTPs requests and parses the response. The operation can require up to a minute to complete. I must prevent the "convoy effect": each call must be executed without waiting for the previous one to complete.

PECL pthread is not an option due to server constraints.

Any ideas?


Solution

  • As far as I know you cannot do what you are looking for.

    Instead of calling a function with its parameters, you have to call another cli php script in a nonblocking manner and put your function in that script.

    This is your main script:

    callDoWork($param1);
    callDoWork($param2);
    callDoWork($param3);
    
    function callDoWork($param){
        $cmd = 'start "" /b php doWork.php '.$param;
        //if $param contains spaces or other special caracters for the command line,
        // you have to escape them.
        pclose(popen($cmd);
    }
    

    doWork.php would look like :

    if(is_array($_SERVER['argv'])) $param = $_SERVER['argv'][1];
    doWork($param);
    function doWork($data)
    {
        //do stuff, write result to db
    }
    

    More information about argv.