Best method for running parallel PHP scripts

154 Views Asked by At

I'd like to run 3 different simple scripts at once that each scrapes websites content and returns a string. Which of the pcntl, pthreads, background exec() methods is most suitable? I'm mostly interested in low resource consumption.

2

There are 2 best solutions below

1
On

It is hard to answer generally.

Which resource you want to optimise?

Anyway the first example here answers your question mostly: http://php.net/manual/en/function.pcntl-fork.php

<?php
for ($i = 1; $i <= 5; ++$i) {
        $pid = pcntl_fork();

        if (!$pid) {
            sleep(1);
            print "In child $i\n";
            exit($i);
        }
    }

    while (pcntl_waitpid(0, $status) != -1) {
        $status = pcntl_wexitstatus($status);
        echo "Child $status completed\n";
    }
?>
0
On

Because I found my host doesn't provide the extensions, the exec way is the only one to go. However pthreads seems to be the most efficient one.