reactphp / reactphp

Event-driven, non-blocking I/O with PHP.

Home Page:https://reactphp.org

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How to run blocking closure in concurrent?

rawaludin opened this issue · comments

Sorry, if this is not the right place. I just don't know where to ask. If its not right, just delete my issue.

So, I've been reading documentation about Event Loop and Promise. Also, some blogpost. I want to understand how reactphp would run blocking code in async.

I have this sample code as a use case I could find:

$uris = [
    "https://google.com/",
    "https://github.com/",
    "https://stackoverflow.com/",
];

$results = [];
foreach ($uris as $uri) {
    var_dump("fetching $uri..");
    $results[$uri] = file_get_contents($uri);
    var_dump("done fetching $uri.");
}

foreach ($results as $uri => $result) {
    var_dump("uri : $uri");
    var_dump("result : " . strlen($result));
}

As you can see the blocking part is file_get_contents. The output would look like this:

string(30) "fetching https://google.com/.."
string(34) "done fetching https://google.com/."
string(30) "fetching https://github.com/.."
string(34) "done fetching https://github.com/."
string(37) "fetching https://stackoverflow.com/.."
string(41) "done fetching https://stackoverflow.com/."
string(25) "uri : https://google.com/"
string(14) "result : 48092"
string(25) "uri : https://github.com/"
string(14) "result : 65749"
string(32) "uri : https://stackoverflow.com/"
string(15) "result : 260394"

So my goal was to process the blocking code file_get_contents in async (not parallel). I believe the output would be something like this:

string(30) "fetching https://google.com/.."
string(30) "fetching https://github.com/.."
string(37) "fetching https://stackoverflow.com/.."
string(34) "done fetching https://google.com/."
string(34) "done fetching https://github.com/."
string(41) "done fetching https://stackoverflow.com/."
string(25) "uri : https://google.com/"
string(14) "result : 48124"
string(25) "uri : https://github.com/"
string(14) "result : 65749"
string(32) "uri : https://stackoverflow.com/"
string(15) "result : 260107"

Am I correct to try to use reactphp to solve that?
How would I achieve that?

@rawaludin Welcome to ReactPHP! :-)

For many blocking things there are non-blocking alternatives. In your example, you may want to take a look at https://github.com/clue/reactphp-buzz/blob/dd9acf2a4413718b10c820931143307c51415e5d/examples/02-concurrent.php. See also https://github.com/reactphp/react/wiki/Users for many possible alternatives.

I hope this helps 👍