Created
December 4, 2014 09:32
-
-
Save polonskiy/6b21065008c21170d9d6 to your computer and use it in GitHub Desktop.
PHProutines
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 | |
// 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()); |
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 | |
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); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Impressive! Looks like
stream_socket_pair
is built into PHP?