2016-08-11 23 views
1

我在phreads中使用了池和Promise(等待線程結果)的組合,但我並不擅長編程。我想獲得變量$變量可訪問的代碼中,我寫了「/ /我不知道如何訪問變量$變量在這裏功能checkvariable」帶池的PHP pthreads並等待收集結果

但我不知道這是否解決我的問題的正確方法是,我想要運行10個線程,並且在每個線程中,我需要運行另外10個線程來返回結果。當結果出現時,前10個線程中的1個執行任務並停止。

我會非常感謝您的幫助! ?

<?php 

class Pool extends Pool { 
    public $data = []; 

    public function process() { 
     // Run this loop as long as we have 
     // jobs in the pool 
     while (count($this->work)) { 
      $this->collect(function (CheckThis $job) { 
       // If a job was marked as done 
       // collect its results 
       if ($job->isGarbage()) { 
        $this->data[$job->query] = $job->html; 
       } 

       return $job->isGarbage(); 
      }); 
     } 

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

class CheckThis extends Collectable { 
    public function __construct($variable) { 
     $this->variable = $variable; 
    } 

    public function run() { 

     // $this->variable exists here 

     $promise = new Promise(function() { 

      // I don't know how to access the variable $variable here for the function checkvariable 

      return checkvariable($variable); 
     }); 

     $promise->then(function ($results) { 

      if ($results) { 
       workonresult(); 
      } 
     });   

     $this->setGarbage(); 
    } 
} 

class Promise extends Thread { 
    public function __construct(Closure $closure) { 
     $this->closure = $closure; 
     $this->start(); 
    } 

    public function run() { 
     $this->synchronized(function() { 
      $closure = $this->closure; 

      $this->result = $closure(); 
      $this->notify(); 
     }); 
    } 

    public function then(callable $callback) { 
     return $this->synchronized(function() use ($callback) { 
      if (!$this->result) { 
       $this->wait(); 
      } 

      $callback($this->result); 
     }); 
    } 
} 

$pool = new Pool(2, Worker::class); 

$pool->submit(new CheckThis($variable1)); 
$pool->submit(new CheckThis($variable2)); 

$data = $pool->process(); 
var_dump($data); 

>

我嘗試這樣做,但它一點兒也不ofcourse工作:

public function run() { 

     $variable = $this->variable; 

     $promise = new Promise(function ($variable) { 
     return checkvariable($variable); 
    }); 

更新,這並不工作之一:

public function run() { 

    $variable = $this->variable; 

    $promise = new Promise(function() use ($variable) { 
    return checkvariable($variable); 
}); 
+0

您是否在尋找'use'關鍵字? – Chay22

+0

你是什麼意思? – Daniel

+0

我的意思是像我的答案 – Chay22

回答

0

使用use關鍵字

$variable = $this->variable; 

$promise = new Promise(function() use ($variable) { 
    return checkvariable($variable) 
}); 
+0

感謝您的提示,應該已經工作,但我插入該代碼,檢查$變量有一個值之前新的承諾,但在新的承諾它仍然是空的。 – Daniel