Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
PHProutines
<?php
// https://gist.github.com/elimisteve/4442820
// challenge accepted :)
require __DIR__ . '/PHProutines.php';
function intDoubler($ch, $n) {
$ch->write($n * 2);
}
$runner = new Runner;
$ch = new Chan;
$answer = new Chan;
$runner->go('intDoubler', $ch, 10);
$runner->go('intDoubler', $ch, 20);
$runner->go(function($a, $b) use ($ch) {
$ch->write($a + $b);
}, 30, 40);
$runner->go(function() use ($ch, $answer) {
list($x, $y, $z) = [$ch->read(), $ch->read(), $ch->read()];
$answer->write(sprintf('%d + %d + %d = %d', $x, $y, $z, $x + $y + $z));
});
printf("%s\n", $answer->read());
<?php
class Runner {
public function __construct() {
pcntl_signal(SIGCHLD, SIG_IGN);
}
public function go() {
if (pcntl_fork()) return;
$args = func_get_args();
$func = array_shift($args);
call_user_func_array($func, $args);
die;
}
}
class Chan {
protected $size;
protected $in;
protected $out;
public function __construct($size = 8192) {
$this->size = $size;
list($this->in, $this->out) = stream_socket_pair(
STREAM_PF_UNIX,
STREAM_SOCK_DGRAM,
STREAM_IPPROTO_IP
);
}
public function read() {
return fread($this->in, $this->size);
}
public function write($data) {
return fwrite($this->out, $data);
}
}

elimisteve commented Jul 18, 2016

Impressive! Looks like stream_socket_pair is built into PHP?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment