Created
January 8, 2015 21:04
-
-
Save vadim2404/25d6cc88bf70e14c282a to your computer and use it in GitHub Desktop.
This file contains 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
#!/usr/bin/env php | |
<?php | |
$jobs = new \SplQueue(); | |
$workers = (int) `nproc`; | |
for ($i = 0; $i < 5 * $workers; ++$i) { | |
$jobs->enqueue(rand(100, 500)); | |
} | |
`rm -f /tmp/server.sock`; | |
$socket = stream_socket_server('unix:///tmp/server.sock', $errno, $errstr); | |
if (!$socket) { | |
die (sprintf("Socket error: %d %s", $errno, $errstr)); | |
} | |
while (!$jobs->isEmpty()) { | |
if ($conn = stream_socket_accept($socket)) { | |
fwrite($conn, $jobs->shift()); | |
fclose($conn); | |
} | |
} | |
fclose($socket); |
This file contains 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
#!/usr/bin/env php | |
<?php | |
$workersCount = (int) `nproc`; | |
for ($i = 0; $i < $workersCount - 1; ++$i) { | |
$pid = pcntl_fork(); | |
if (-1 === $pid) { | |
die('Fork error'); | |
} | |
if (0 === $pid) { | |
break; | |
} | |
} | |
while ($socket = stream_socket_client('unix:///tmp/server.sock', $errno, $errstr)) { | |
if (false === $socket) { | |
die(sprintf("Can not create a socket: %d %s", $errno, $errstr)); | |
} | |
$job = ''; | |
while (!feof($socket)) { | |
$job .= fgets($socket, 1024); | |
} | |
fclose($socket); | |
if ('' === $job) { | |
continue; | |
} | |
$file = fopen('/tmp/results.txt', 'a'); | |
while (!flock($file, LOCK_EX)) { | |
sleep(1); | |
} | |
fwrite($file, sprintf("Pid: %d, Job: %d, Result: %d\n", posix_getpid(), $job, 2 * $job)); | |
flock($file, LOCK_UN); | |
fclose($file); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment