/**
  * @param integer $iterations how many
  * @param integer $addressToReport address to send reports about calculation
  * @return \Closure
  */
 public function getCalculatorHandler($iterations, $addressToReport)
 {
     return function ($message, $state) use($iterations, $addressToReport) {
         if (!isset($state['calculator'])) {
             $state['calculator'] = new Calculator(1000);
         }
         if (!isset($state['sendReport'])) {
             $state['sendReport'] = function ($state) use($addressToReport) {
                 \Phactor\Phactor\Actor::sendMessage($addressToReport, serialize(\Phactor\App\Report::factory($state['mailbox']->getAddress(), $state['calculator']->getCounters(), $state['calculator']->getResult())));
             };
         }
         if ($message === 'start') {
             for ($i = 0; $i < $iterations; $i += 1000) {
                 for ($j = 0; $j < 1000; ++$j) {
                     $state['calculator']->step();
                 }
                 if ($connection = $state['mailbox']->fetchMessage()) {
                     if (stream_get_contents($connection) === 'report') {
                         $state['sendReport']($state);
                     }
                 }
             }
             $state['sendReport']($state);
         } elseif ($message === 'report') {
             $state['sendReport']($state);
         }
         return $state;
     };
 }
示例#2
0
文件: main.php 项目: elnoro/phactor
<?php

require __DIR__ . '/vendor/autoload.php';
$startTime = time();
$config = (require __DIR__ . '/config.php');
\Phactor\Phactor\App::launch($config['appAddress'], function ($message, $state) use($startTime) {
    if ($message === '') {
        \Phactor\Phactor\Actor::createAndRun($state['aggregatorAddress'], function ($message, $state) use($startTime) {
            if (!isset($state['aggregator'])) {
                $state['aggregator'] = new \Phactor\App\WebAggregator(__DIR__ . '/index.html', $startTime);
            }
            $state['aggregator']->addReport(unserialize($message));
            $state['aggregator']->dump();
            return $state;
        });
        $service = new \Phactor\App\CalculatorMultiProcessService($state['numberOfProcesses'], $state['aggregatorAddress']);
        $service->start();
        while (true) {
            sleep(rand(1, 100));
            echo 'Asking for report...' . PHP_EOL;
            foreach ($service->getAddresses() as $calculatorAddress) {
                \Phactor\Phactor\Actor::sendMessage($calculatorAddress, 'report');
            }
        }
    }
    return $state;
}, $config);