How does Pool::collect works?

后端 未结 2 1624
北荒
北荒 2021-01-14 07:47

Help me understand how exactly Pool::collect works.

Pool::collect — Collect references to completed tasks

public void Pool::collect          


        
2条回答
  •  猫巷女王i
    2021-01-14 08:14

    Pool::collect traverses a list of objects passing each one to the $collector.

    The $collector function should return true when the engine can destroy the reference to the Threaded object in the work list.

    In PHP7

    The ::collect functionality was moved to Worker, though it's still exposed by Pool for utility.

    There are two lists, one list of items ready to be executed, and another of items that have been executed (or is currently being executed).

    Pool::collect traverses the second list, items that have been executed (or is currently being executed).

    Pool::collect returns the number of items still left in the garbage list for all Worker objects in the Pool to aid with scheduling garbage collection.

    PHP7 Code

    submit(new class($i) extends Threaded {
            public function __construct($id) {
                $this->id = $id;
            }
    
            public function run() {
                printf(
                    "Hello World from %d\n", $this->id);
            }
    
            public $id;
        });
    }
    
    while ($pool->collect(function(Collectable $work){
        printf(
            "Collecting %d\n", $work->id);
        return $work->isGarbage();
    })) continue;
    
    $pool->shutdown();
    ?>
    

    Will yield something like:

    Hello World from 1
    Hello World from 2
    Hello World from 3
    Hello World from 4
    Hello World from 8
    Collecting 1
    Hello World from 7
    Hello World from 5
    Collecting 5
    Hello World from 6
    Collecting 9
    Collecting 2
    Collecting 6
    Collecting 10
    Hello World from 9
    Collecting 3
    Collecting 7
    Collecting 4
    Hello World from 10
    Collecting 8
    Collecting 5
    Collecting 10
    

提交回复
热议问题