PHP 5.6.0RC3 is available

Worker 类

(PECL pthreads >= 2.0.0)

简介

Worker 是一个具有持久化上下文的线程对象,通常用来重复使用线程。

当一个 Worker 对象开始之后,会执行它的 run 方法,但是即使 run 方法执行完毕,线程本身也不会消亡,除非遇到以下情况:

  • Worker 对象超出作用范围(没有指向它的引用了)

  • 代码调用了 Worker 对象的 shutdown 方法

  • 整个脚本终止了

这意味着程序员可以在程序执行过程中重用这个线程上下文:在 Worker 对象的栈中添加对象会激活 Worker 对象执行被加入对象的 run 方法。

Warning

程序员必须保持入栈对象的引用,直到它执行完毕或者出栈。Pool 类提供了 Worker 对象的高层抽象, 它可以帮助程序员管理这些引用。

类摘要

Worker extends Thread implements Traversable , Countable , ArrayAccess {
/* 方法 */
public integer getStacked ( void )
public boolean isShutdown ( void )
public boolean isWorking ( void )
public boolean shutdown ( void )
public integer stack ( Threaded &$work )
public integer unstack ([ Threaded &$work ] )
/* 继承的方法 */
public void Thread::detach ( void )
public integer Thread::getCreatorId ( void )
public static Thread Thread::getCurrentThread ( void )
public static integer Thread::getCurrentThreadId ( void )
public integer Thread::getThreadId ( void )
public static mixed Thread::globally ( void )
public boolean Thread::isJoined ( void )
public boolean Thread::isStarted ( void )
public boolean Thread::join ( void )
public void Thread::kill ( void )
public boolean Thread::start ([ integer $options ] )
}

Table of Contents

add a note add a note

User Contributed Notes 1 note

up
5
event2game at gmail dot com
9 months ago
There's one way to shared datas between Workers, that is using Stackable:
<?php
class data extends Stackable{
   
//private $name;
   
public function __construct($_name) {
       
//$this->name = $_name;//if you set any variable, workers will get the variable, so do not set any variable
       
echo __FILE__.'-'.__LINE__.'<br/>'.chr(10);
    }
    public function
run(){
        echo
__FILE__.'-'.__LINE__.'<br/>'.chr(10);
    }
}
class
readWorker extends Worker {
    public function
__construct(&$_data) {
       
$this->data = $_data;//
   
}
    public function
run(){
        while(
1){
            if(
$arr=$this->data->shift())//receiving datas
           
{
                echo
'Received data:'.print_r($arr,1).chr(10);
            }else
usleep(50000);
        }
    }
}
class
writeWorker extends Worker {
    public function
__construct(&$_data) {
       
$this->data = $_data;//
   
}
    public function
run(){
        while(
1){
           
$this->data[] = array(time(),rand());//writting datas
           
usleep(rand(50000, 1000000));
        }
    }

}
$data = new data('');
$reader = new readWorker($data);
$writer = new writeWorker($data);
$reader->start();
$writer->start();
?>
Also you can use $readWorker[] = $some_data; then use $this->shift() in readWorker to share datas with readWorker, but if you do so you can't have variables in readWorker as all variales will be shift by shift();
To Top