spawn() public static method

Spawns a new forked process and runs it.
public static spawn ( callable $function, $args ) : self
$function callable A callable to invoke in the process.
return self The process object that was spawned.
示例#1
0
#!/usr/bin/env php
<?php 
require dirname(__DIR__) . '/vendor/autoload.php';
use Icicle\Concurrent\Forking\Fork;
use Icicle\Coroutine;
use Icicle\Loop;
Coroutine\create(function () {
    $context = Fork::spawn(function () {
        print "Child sleeping for 4 seconds...\n";
        sleep(4);
        yield from $this->send('Data sent from child.');
        print "Child sleeping for 2 seconds...\n";
        sleep(2);
        return 42;
    });
    $timer = Loop\periodic(1, function () use($context) {
        static $i;
        $i = $i ? ++$i : 1;
        print "Demonstrating how alive the parent is for the {$i}th time.\n";
    });
    try {
        printf("Received the following from child: %s\n", yield from $context->receive());
        printf("Child ended with value %d!\n", yield from $context->join());
    } catch (Exception $e) {
        print "Error from child!\n";
        print $e . "\n";
    } finally {
        $timer->stop();
    }
});
Loop\run();
示例#2
0
 /**
  * @inheritdoc
  *
  * @param string $key
  * @param mixed $value
  *
  * @return PromiseInterface
  *
  * @resolve mixed
  */
 public function set($key, $value)
 {
     $deferred = new Deferred();
     Loop\queue(function () use($deferred, $key, $value) {
         if ($this->busy($deferred, $key)) {
             $this->wait($deferred, $key);
         } else {
             Coroutine\create(function () use($deferred, $key, $value) {
                 $this->busy[$key] = $deferred;
                 if (is_callable($value)) {
                     $fork = Fork::spawn($value);
                     $value = (yield $fork->join());
                 }
                 $this->cache[$key] = $value;
                 unset($this->busy[$key]);
                 if (isset($this->waiting[$key])) {
                     while (count($this->waiting[$key])) {
                         /** @var Deferred $next */
                         $next = array_shift($this->waiting[$key]);
                         $next->resolve($value);
                     }
                 }
                 $deferred->resolve($value);
             });
         }
     });
     return $deferred->getPromise();
 }