我想用pthreads编写一些PHP代码。对于这个pthreads,我需要知道有多少线程处于活动状态。因为下一个系统只能处理固定数量的请求。我可以计算已启动的线程,但是当线程停止时我无法减去。
我试图计算线程对象的数量,但我也没有减去。我如何管理,如果一个主题完成了他的工作,我会获得一个信息到我的起始脚本?
答案 0 :(得分:2)
我找到了获取有关运行和未运行线程的信息的方法。所以我可以数数吧。如果有人有更好的解决方案,我很高兴看到它。但首先我要分享我自己的解决方案。
#!/usr/bin/php
<?php
class AsyncOperation extends Thread
{
public function __construct($threadId)
{
$this->threadId = $threadId;
}
public function run()
{
printf("T %s: Sleeping 3sec\n", $this->threadId);
sleep(1);
printf("T %s: Hello World\n", $this->threadId);
$this->kill;
}
}
$a=0;
$start = microtime(true);
for ($i = 1; $i <= 5; $i++) {
$test[$i] = new AsyncOperation($i);
$test[$i]->start();
}
$arg=true;
while($arg){
$arg=false;
foreach($test as $key => $object){
// for ($i = 1; $i <= 5; $i++) {
$arg2=$object->isRunning();
if($arg2){
$arg=$arg2;
}else{
//var_dump($key);
unset ($test[$key]);
}
//var_dump($key);
if(!$arg){
var_dump($arg);
}
}
}
var_dump($test);
echo count($test)."\n";
echo "\n".microtime(true) - $start . "\n";
echo "end\n";
答案 1 :(得分:1)
池类,是工作线程的集合。 通过可调整的线程数,您可以设置具有特定工作线程数的池来做一个作业列表,多线程方式。
比方说,你只想创建3个线程,处理10个工作。
<?php
class MyWork extends Threaded {
public $name;
public function __construct($name) {
echo "Constructing worker $name \n";
$this->name = $name;
}
public function run() {
echo "Worker $this->name start running\n";
$strMem = '[mem:' . (memory_get_usage(true) / 1024 / 1024). 'MB]';
for ($i = 1; $i <= 5; $i++) {
/*
random delay is to simulate different time it takes for this worker to process the job.
in the real work, this is where the job is done
*/
$delay = rand(1,5); //busy... busy...
echo "Worker $this->name : $i process in [$delay s] $strMem \n";
sleep($delay);
}
}
}
class MyWorker extends Worker {
public function run() {}
}
ini_set('max_execution_time', 7200);
ini_set('output_buffering ',0);
$sJob = "A";//starting job
$iMaxJob = 10;//max job
$iMaxThread = 3;//create a pool for 3 worker;
$pool = new Pool($iMaxThread);
//start queing jobs;
for ($i=1; $i <= $iMaxJob; $i++){
$pool->submit(new MyWork($sJob++));
}
$pool->shutdown();
$strMem = '[peak:' . (memory_get_peak_usage(true) / 1024 / 1024). 'MB]';
echo "done. " . $strMem;
?>