PHP 7.0.6 Released

The Thread class

(PECL pthreads >= 2.0.0)

Introduction

When the start method of a Thread is invoked, the run method code will be executed in separate Thread, in parallel.

After the run method is executed the Thread will exit immediately, it will be joined with the creating Thread at the appropriate time.

Warning

Relying on the engine to determine when a Thread should join may cause undesirable behaviour; the programmer should be explicit, where possible.

Class synopsis

Thread extends Threaded implements Countable , Traversable , ArrayAccess {
/* Methods */
public void detach ( void )
public integer getCreatorId ( void )
public static Thread getCurrentThread ( void )
public static integer getCurrentThreadId ( void )
public integer getThreadId ( void )
public static mixed globally ( void )
public boolean isJoined ( void )
public boolean isStarted ( void )
public boolean join ( void )
public void kill ( void )
public boolean start ([ integer $options ] )
/* Inherited methods */
public array Threaded::chunk ( integer $size , boolean $preserve )
public integer Threaded::count ( void )
public bool Threaded::extend ( string $class )
public Threaded Threaded::from ( Closure $run [, Closure $construct [, array $args ]] )
public array Threaded::getTerminationInfo ( void )
public boolean Threaded::isRunning ( void )
public boolean Threaded::isTerminated ( void )
public boolean Threaded::isWaiting ( void )
public boolean Threaded::lock ( void )
public boolean Threaded::merge ( mixed $from [, bool $overwrite ] )
public boolean Threaded::notify ( void )
public boolean Threaded::pop ( void )
public void Threaded::run ( void )
public mixed Threaded::shift ( void )
public mixed Threaded::synchronized ( Closure $block [, mixed $... ] )
public boolean Threaded::unlock ( void )
public boolean Threaded::wait ([ integer $timeout ] )
}

Table of Contents

User Contributed Notes

312036773 at qq dot com
4 months ago
<?php
class STD extends Thread{
    public function
put(){
       
       
$this->synchronized(function(){
            for(
$i=0;$i<7;$i++){

   
printf("%d\n",$i);
   
$this->notify();
    if(
$i < 6)
   
$this->wait();
    else
        exit();
   
sleep(1);
}
        });

    }

        public function
flush(){
       
$this->synchronized(function(){
            for(
$i=0;$i<7;$i++){
   
flush();
   
$this->notify();
    if(
$i < 6)
   
$this->wait();
    else
        exit();
    }
});
}
}

class
A extends Thread{
    private
$std;
    public function
__construct($std){
       
$this->std = $std;
    }
    public function
run(){
       
$this->std->put();
    }
}

class
B extends Thread{
    private
$std;
    public function
__construct($std){
       
$this->std = $std;
    }
    public function
run(){
       
$this->std->flush();
    }
}
ob_end_clean();
echo
str_repeat(" ", 1024);
$std = new STD();
$ta = new A($std);
$tb = new B($std);
$ta->start();
$tb->start();
german dot bernhardt at gmail dot com
2 years ago
<?php

class workerThread extends Thread {
public function
__construct($i){
 
$this->i=$i;
}

public function
run(){
  while(
true){
   echo
$this->i;
  
sleep(1);
  }
}
}

for(
$i=0;$i<50;$i++){
$workers[$i]=new workerThread($i);
$workers[$i]->start();
}

?>
german dot bernhardt at gmail dot com
1 month ago
# ERROR GLOBAL VARIABLES IMPORT

$tester=true;

function tester(){
global $tester;
var_dump($tester);
}

tester(); // PRINT -> bool(true)

class test extends Thread{
public function run(){
  global $tester;
  tester(); // PRINT -> NULL
}
}
$workers=new test();
$workers->start();
66377393 at qq dot com
1 year ago
<?php
class demo extends Thread{
    public
$num = 0;
    public function
__construct($num){
       
$this->num = $num+200;
    }

    public function
run(){
       
//当执行start方法时,run会执行,所以没有直接调用run的方法
       
return $this->num;
    }
}

//时间计算开始
$t = microtime(true);
for(
$i = 0 ;$i < 10 ; $i++){
   
//创建线程池
   
$pool[] = new demo($i);
}

foreach(
$pool as $work){
   
//在独立线程中执行 run 方法
   
$work->start();
}

foreach(
$pool as $key=>$value){
   
//对象是否正在运行
   
while($value->isRunning()){
       
usleep(10);
    }
   
//让当前执行上下文等待被引用线程执行完毕
   
if($value->join()){
       
$row[$key] = $value->num;
    }
}
//时间计算结束
$e = microtime(true);

var_dump($row);
echo
'<br />';
echo (
$e-$t);
hanscastroadmn at gmail dot com
2 years ago
/*
    Programa para generar diccionarios de fuerza bruta con
    diferentes hilos usando Thread en PHP 5.4
*/

class FuerzaBruta extends Thread
{
    private $n;
    private $out;
    private $smap;
   
    public function FuerzaBruta($numero)
    {
        $this->n = $numero; // Numero de caracteres
       
        $this->smap = ['a','b','c','d'];
       
        $this->start();
    }
   
    public function run(){
        for($i = 0; $i < pow(count($this->smap), $this->n) - 1; $i++){
           $this->visualizar();
           $this->siguiente();
        }
       
        $this->visualizar();
    }
   
    public function siguiente(){
        $this->out[0]++;
        $m = 0;
        while($this->out[$m] == count($this->smap)){
            $this->out[$m++] = 0;
            $this->out[$m]++;
        }
    }
   
    public function visualizar(){
        $output = "";
        for($i = 0;$i < $this->n; $i++){
            $output += $this->smap[$this->out[$i]];
        }
       
        echo $output;
    }
   
}

//Genera todas las combinaciones de 5 caracteres.
for($i = 1; $i < 5; $i++) new FuerzaBruta($i);

// Algún error tendré...
actrace at icloud dot com
2 years ago
<?php

class vote extends Thread {

    public
$res    = '';
    public
$url    = array();
    public
$name   = '';
    public
$runing = false;
    public
$lc     = false;

    public function
__construct($name) {

       
$this->res    = '暂无,第一次运行.';
       
$this->param    = 0;
       
$this->lurl   = 0;
       
$this->name   = $name;
       
$this->runing = true;
       
$this->lc     = false;
    }

    public function
run() {
        while (
$this->runing) {

            if (
$this->param != 0) {
               
$nt          = rand(1, 10);
                echo
"线程[{$this->name}]收到任务参数::{$this->param},需要{$nt}秒处理数据.\n";
               
$this->res   = rand(100, 999);
               
sleep($nt);
               
$this->lurl = $this->param;
               
$this->param   = '';
            } else {
                echo
"线程[{$this->name}]等待任务..\n";
            }
           
sleep(1);
        }
    }

}

//这里创建线程池.
$pool[] = new vote('a');
$pool[] = new vote('b');
$pool[] = new vote('c');

//启动所有线程,使其处于工作状态
foreach ($pool as $w) {
   
$w->start();
}

//派发任务给线程
for ($i = 1; $i < 10; $i++) {
   
$worker_content = rand(10, 99);
    while (
true) {
        foreach (
$pool as $worker) {
           
//参数为空则说明线程空闲
           
if ($worker->param=='') {
               
$worker->param = $worker_content;
                echo
"[{$worker->name}]线程空闲,放入参数{$worker_content},上次参数[{$worker->lurl}]结果[{$worker->res}].\n";
                break
2;
            }
        }
       
sleep(1);
    }
}
echo
"所有线程派发完毕,等待执行完成.\n";

//等待所有线程运行结束
while (count($pool)) {
   
//遍历检查线程组运行结束
   
foreach ($pool as $key => $threads) {
        if (
$worker->param=='') {
            echo
"[{$threads->name}]线程空闲,上次参数[{$threads->lurl}]结果[{$threads->res}].\n";
            echo
"[{$threads->name}]线程运行完成,退出.\n";
           
//设置结束标志
           
$threads->runing = false;
            unset(
$pool[$key]);
        }
    }
    echo
"等待中...\n";
   
sleep(1);
}
echo
"所有线程执行完毕.\n";
?>

父线程可以操作子线程变量,可以先启动一组线程等待来自父线程的参数,然后再工作.
To Top