PHP pthreads无法杀死线程(&超时实现)

时间:2015-04-12 04:35:26

标签: php multithreading pthreads

我有一个示例代码。它的作用是访问页面。我想为线程执行做超时,并在挂起太久时将其关闭。我认为有内置的方法来实现它。另外,我已经尝试通过time()函数自己完成它。但还有另一个问题。此时$workers[$i]->kill();脚本挂起,kill()方法返回false,因此我无法强制关闭线程。发生了什么,我做错了什么? 谢谢!

<?php

/**
* Author: Abu Ashraf Masnun
* URL: http://masnun.me
*/
//define("TMT",3); 

class WorkerThreads extends Thread
{
    private $workerId;

    public function __construct($string)
    {
        $this->command_string = trim($string);
    }

    public function run()
    {

        echo $this->command_string." ".Thread::getCurrentThreadId()."\n";
    //sleep(rand(0, 3));
    $str = "C:\\Users\\Alex\\Desktop\\2web\\phantom\\phantomjs.exe C:\\Users\\Alex\\Desktop\\2web\\test.js ";

    $url = $this->command_string;
    $d = explode("://",$url);
    $ex_str = $str." ".$url." > ".$d[1].".html";
    //$ex_str = $str." ".$url;
    //echo $ex_str;
    //$ex_str =  escapeshellarg($ex_str);
    //echo $ex_str; 

    exec($ex_str, $out);

    //print_r($out);
    }
}

//$data = file('sites.txt'); 
$data_f = file('sites_x.txt');
print_r($data_f);
$data = array();
$data_size = count($data_f);
for($i = 0;$i<$data_size;$i++)
{
  $info = explode(";",trim($data_f[$i]));
  if($info[1] === 'y')
    continue;
  $data[] = $info[0];
}
print_r($data);
$data_size = count($data);
// Worker pool
$workers = [];
$t_count = 4;
$flag = 1;
$k = 0;
//echo "$data_size";

while($flag === 1)
{   


  /*
  //echo "$k\n";
  if($k >= $data_size)
  { 
    //echo "111"; exit();
    $flag = 0;
    break 2;
  }
  */
  $c_w = count($workers);

  if($c_w < $t_count)
  {
    for($i = $c_w; $i<$t_count - $c_w;$i++)
    {
      if($k >= $data_size)
      {
        $flag = 0;
        break;
      } 

      $workers[$i] = new WorkerThreads($data[$k]);
      //echo $data[$k]."\n";
      echo "worker $i started\n";
      $workers[$i]->start();
      $k++; 
    }

  }

  $c_w = count($workers);
  for($i=0;$i<$c_w;$i++)
  {

      $workers[$i]->kill();
      unset($workers[$i]);
      echo "unset $i\n";
      //var_dump($workers[$i]->isTerminated(), $workers[$i]->getTerminationInfo());
      /*
      if($workers[$i]->join())
      {
        //var_dump($workers[$i]->isTerminated(), $my->getTerminationInfo());
        echo "joining $i\n";
        unset($workers[$i]);

      } 
      */
  }


}

?>

1 个答案:

答案 0 :(得分:0)

今天我用pthreads 2.0.10遇到了这个问题。

从源代码重新编译PHP以获得ZTS支持后,我尝试构建pthreads(phpize,configure,make)。在我运行make test之前,一切似乎都没问题。在30秒超时后,killed-info测试失败。

我的解决方案是从master branch on github编译最新的pthread。