This repository was archived by the owner on Dec 8, 2024. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparallel.php
78 lines (59 loc) · 1.92 KB
/
parallel.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
<?php
use Symfony\Component\Process\Process;
require __DIR__ . '/vendor/autoload.php';
$script = array_shift($argv);
if ($argc < 4) {
printf('Usage: %s rate concurrency command' . PHP_EOL, $script);
echo ' rate The number of executions per second', PHP_EOL;
echo ' concurrency The maximum number of concurrent processes', PHP_EOL;
echo ' command The command to execute', PHP_EOL;
exit(1);
}
$rate = array_shift($argv);
$concurrency = array_shift($argv);
if (preg_match('/^[0-9]+(?:\.[0-9]+)?$/', $rate) !== 1) {
printf('%s is not a valid value for rate.' . PHP_EOL, $rate);
}
if (preg_match('/^[0-9]+$/', $concurrency) !== 1) {
printf('%s is not a valid value for concurrency.' . PHP_EOL, $concurrency);
exit(1);
}
$rate = (float) $rate;
$concurrency = (int) $concurrency;
if ($rate === 0.0) {
echo 'rate cannot be zero.', PHP_EOL;
exit(1);
}
if ($concurrency === 0) {
echo 'concurrency cannot be zero.', PHP_EOL;
exit(1);
}
$command = $argv;
$sleepTime = (int) (1000000.0 / $rate);
$processes = [];
$filter = static function(Process $process) {
return $process->isRunning();
};
for (;;) {
$time = microtime(true);
$processes = array_values(array_filter($processes, $filter));
if (count($processes) < $concurrency) {
$process = new Process($command);
$process->start(static function($type, $data) {
if ($type === Process::OUT) {
fwrite(STDOUT, $data);
} elseif ($type === Process::ERR) {
fwrite(STDERR, $data);
} else {
echo 'Unknown output type ', $type, PHP_EOL;
exit(1);
}
});
$processes[] = $process;
}
$microsecondsSpent = (int) (1000000 * (microtime(true) - $time));
$microsecondsSleep = $sleepTime - $microsecondsSpent;
if ($microsecondsSleep > 0) {
usleep($microsecondsSleep);
}
}