Created
June 20, 2018 20:15
-
-
Save 421p/3750a0932dee7d3087d7842ecdf5960c to your computer and use it in GitHub Desktop.
pthreads-reactphp
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"require": { | |
"iainconnor/composer-pthreads": "^1.0" | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
use IainConnor\ComposerPthreads\AutoloadWorker; | |
use IainConnor\ComposerPthreads\ResponseDataBundle; | |
use Pool; | |
use React\EventLoop\LoopInterface; | |
use React\Promise\Deferred; | |
use React\Promise\PromiseInterface; | |
class Executor | |
{ | |
private $pool; | |
private $loop; | |
public function __construct(LoopInterface $loop) | |
{ | |
$this->loop = $loop; | |
$this->pool = new Pool(4, AutoloadWorker::class, [__DIR__.'/../../autoload.php']); | |
} | |
public function shutdown() | |
{ | |
$this->pool->shutdown(); | |
} | |
public function async(callable $closure): PromiseInterface | |
{ | |
$defer = new Deferred(); | |
$data = new ResponseDataBundle(); | |
$task = new Task($closure, $data); | |
$this->pool->submit($task); | |
$listener = function () use (&$listener, $data, $task, $defer) { | |
if ($task->isDone()) { | |
$defer->resolve($data->getData()); | |
} else { | |
$this->loop->futureTick($listener); | |
} | |
}; | |
$this->loop->futureTick($listener); | |
return $defer->promise(); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
use IainConnor\ComposerPthreads\ResponseDataBundle; | |
class Task extends \Volatile | |
{ | |
private $closure; | |
private $data; | |
private $done = false; | |
public function __construct(callable $closure, ResponseDataBundle $data) | |
{ | |
$this->data = $data; | |
$this->closure = $closure; | |
} | |
public function run() | |
{ | |
$this->data->setData(($this->closure)()); | |
$this->done = true; | |
} | |
public function isDone(): bool | |
{ | |
return $this->done; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment