How does Pool::collect works?

后端 未结 2 1595
北荒
北荒 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条回答
  •  一向
    一向 (楼主)
    2021-01-14 08:24

    You missed the audit cycle. Task can not be completed immediately, so at first the collect function do not receive positive result. Several times need to check, it requires a cycle.

    In the example if infinite is true, always 4 tasks working. Otherwise, if size of queue is equal with pool size (4), it is over, you can exit the loop.

    result = md5(rand(1, 2000));
            sleep(rand(1, 5));
            $this->completed = true;
        }
    
        public function isCompleted()
        {
            return $this->completed;
        }
    
        public function getResult()
        {
            return $this->result;
        }
    }
    
    $infinite = false;
    $poolSize = 4;
    $queue = array();
    
    $pool = new \Pool($poolSize);
    $pool->submit(new Task);
    $pool->submit(new Task);
    $pool->submit(new Task);
    $pool->submit(new Task);
    
    
    do {
        if($infinite === true){
            $queue = array();
        }
    
        $pool->collect(function (\Task $task) use (&$queue) {
            if ($task->isCompleted()) {
                echo "Collect task\n";
                $queue[] = $task->getResult();
    
                return true;
            } else {
                echo "task not complete\n";
    
                return false;
            }
        });
    
        $size = sizeof($queue);
        if ($size > 0) {
    
            echo $size . " result\n";
            print_r($queue);
    
            if($infinite === true) {
                for ($m = 0; $m < $size; $m++) {
                    $pool->submit(new Task);
                }
            } else{
                if($size == $poolSize){
                    break;
                }
            }
        }
    
        usleep(100000);
    
    } while (true);
    $pool->shutdown();
    

提交回复
热议问题