Migrate from parallel-function
4khobta opened this issue · 3 comments
4khobta commented
Old working code:
<?php
use function Amp\ParallelFunctions\parallelMap;
use function Amp\Promise\wait;
for ($i = 10; $i < 100; ++$i) {
$ips[] = '192.168.225.' . $i;
}
$responses = wait(parallelMap($ips, function ($ip) {
$snmp = new SNMP(SNMP::VERSION_2c, $ip, 'public');
$ifnames = $snmp->walk('.1.3.6.1.2.1.31.1.1.1.1');
print_r($ifnames);
}));
?>
How to migrate to parallel?
All my attempts were unsuccessful
kelunik commented
How does your attempt look like?
4khobta commented
Thanks. I solved the problem, here is the working code.
Non-blocking native snmp
main.php
<?php
declare(strict_types=1);
require __DIR__ . '/vendor/autoload.php';
use mysnmp\SnmpTask;
use Amp\Future;
use Amp\Parallel\Worker;
use function Amp\async;
for ($i = 10; $i < 100; ++$i) {
$ips[] = '192.168.225.' . $i;
}
$executions = [];
foreach ($ips as $ip) {
$executions[$ip] = Worker\submit(new SnmpTask($ip));
}
$responses = Future\await(array_map(
fn(Worker\Execution $e) => $e->getFuture(),
$executions,
));
foreach ($responses as $ip => $response) {
print_r($response);
}
src/SnmpTask.php
<?php
namespace mysnmp;
use Amp\Cancellation;
use Amp\Parallel\Worker\Task;
use Amp\Sync\Channel;
class SnmpTask implements Task
{
public function __construct(private readonly string $ip,)
{
}
public function run(Channel $channel, Cancellation $cancellation): bool|array
{
$snmp = new \SNMP(\SNMP::VERSION_2c, $this->ip, 'public');
return $snmp->walk('.1.3.6.1.2.1.31.1.1.1.1');
}
}
kelunik commented
Exactly like that, yes. 🙂