SkyRar
SkyRar

Reputation: 1277

How to run methods in Parallel in php without using any extension?

Is it possible to run two methods in parallel without using any extension like pthread or pcntl?

I tried Symfony/Process but it seems like I can use it only for php cli programing.

My requirement is for php web application. I found amphp/parallel that says it works without any extension. I tried the below example. Though I don't know if the library provides true parallel functionality or something else like queuing tasks? Because it is commented below "without any extension parallel processing is not possible".

Before I try the amphp/parallel I wanted to be sure if the library which I found is the right one for my job. Let's say I want to run two methods test1() and test2() in parallel and use the result from those two methods in next line.

    <?php

    require __DIR__ . '/../vendor/autoload.php';

    use Amp\Parallel\Worker;
    use Amp\Promise;

    $urls = [
        'https://secure.php.net',
        'https://amphp.org',
        'https://github.com',
    ];

    $promises = [];
    foreach ($urls as $url) {
        $promises[$url] = Worker\enqueueCallable('file_get_contents', $url);
    }

    $responses = Promise\wait(Promise\all($promises));

    foreach ($responses as $url => $response) {
        \printf("Read %d bytes from %s\n", \strlen($response), $url);
test1(){
   // do some database query
}

test2(){
  // run a lengthy for loop
}

Upvotes: 1

Views: 1153

Answers (0)

Related Questions