Executing functions in parallel

前端 未结 6 1671
情歌与酒
情歌与酒 2020-12-16 18:55

I have a function that needs to go over around 20K rows from an array, and apply an external script to each. This is a slow process, as PHP is waiting for the script to be e

6条回答
  •  情书的邮戳
    2020-12-16 19:35

    you can use "PTHREADS"

    very easy to install and works great on windows

    download from here -> http://windows.php.net/downloads/pecl/releases/pthreads/2.0.4/

    Extract the zip file and then

    • move the file 'php_pthreads.dll' to php\ext\ directory.

    • move the file 'pthreadVC2.dll' to php\ directory.

    then add this line in your 'php.ini' file:

    extension=php_pthreads.dll
    

    save the file.

    you just done :-)

    now lets see example of how to use it:

    class ChildThread extends Thread {
        public $data;
    
        public function run() {
            /* Do some expensive work */
    
            $this->data = 'result of expensive work';
        }
    }
    
    $thread = new ChildThread();
    
    if ($thread->start()) {     
        /*
         * Do some expensive work, while already doing other
         * work in the child thread.
         */
    
        // wait until thread is finished
        $thread->join();
    
        // we can now even access $thread->data
    }
    

    for more information about PTHREADS read php docs here:

    PHP DOCS PTHREADS

    • if you'r using WAMP like me, then you should add 'pthreadVC2.dll' into \wamp\bin\apache\ApacheX.X.X\bin and also edit the 'php.ini' file (same path) and add the same line as before

      extension=php_pthreads.dll

    GOOD LUCK!

提交回复
热议问题