线程PHP代码不是确定性的

时间:2017-02-07 15:10:07

标签: php multithreading pthreads

我有以下代码,使用zts-php 5.6.25运行pthreads 2.0.10。问题是,它应该转储具有以下值的数组:

array(2) {
  [0]=>
  string(3) "abc"
  [1]=>
  string(3) "def"
}

但有时结果数组如下所示:

array(1) {
  [0]=>
  string(3) "abc"
}

我感到困惑,为什么会发生这种情况。也许我错过了一些基本的线程相关规则,但似乎无法理解它。有什么想法吗?

<?
class LinkChecker extends Threaded 
{
    protected $complete;
    protected $urls;

    public $data = '';

    /**
    * @param array $urls Contains the urls to be checked
    */
    public function __construct($urls)
    {
        $this->complete = false;
        $this->urls = $urls;
    } //function

    public function run()
    {
        foreach($this->urls as $url)
        {
            //usleep(200000);
            $this->data .= $url;
            echo 'X';
        } //foreach

        $this->complete = true;
    } //function

    public function getData()
    {
        return $this->data;
    } //function

    public function isGarbage() 
    {
        return $this->complete;
    } //function
} //LinkChecker


class LinkCheckerPool extends Pool
{
    public $data = array();
    public function process()
    {
        $lastcnt = null;
        // Run this loop as long as we have
        // jobs in the pool
        while (count($this->work) > 0) 
        {
            if ($lastcnt != count($this->work))
            {
                echo $lastcnt = count($this->work)."\n";
            } //if

            $this->collect(function (LinkChecker $task) 
            {
                // If a task was marked as done
                // collect its results
                if ( $task->isGarbage() )
                {
                    echo $task->getData();
                    //this is how you get your completed data back out [accessed by $pool->process()]
                    $this->data[] = $task->getData();
                } //if

                return $task->isGarbage();
            });
        } //while

        // All jobs are done
        // we can shutdown the pool
        $this->shutdown();
        return $this->data;
    } //function
} //class

$pool = new LinkCheckerPool(10);

$pool->submit( new LinkChecker(['a','b','c']) );
$pool->submit( new LinkChecker(['d','e','f']) );

$retArr = $pool->process();

var_dump($retArr); //return the array of results (and maybe errors)

0 个答案:

没有答案