The Worker class

(PECL pthreads >= 2.0.0)

Wstęp

Worker Threads have a persistent context, as such should be used over Threads in most cases.

When a Worker is started, the run method will be executed, but the Thread will not leave until one of the following conditions are met:

  • the Worker goes out of scope (no more references remain)

  • the programmer calls shutdown

  • the script dies

This means the programmer can reuse the context throughout execution; placing objects on the stack of the Worker will cause the Worker to execute the stacked objects run method.

Krótki opis klasy

Worker extends Thread implements Traversable , Countable , ArrayAccess {
/* Metody */
public collect ([ Callable $collector ] ) : int
public getStacked ( void ) : int
public isShutdown ( void ) : bool
public isWorking ( void ) : bool
public shutdown ( void ) : bool
public stack ( Threaded &$work ) : int
public unstack ( void ) : int
/* Metody dziedziczone */
public Thread::detach ( void ) : void
public Thread::getCreatorId ( void ) : int
public static Thread::getCurrentThread ( void ) : Thread
public static Thread::getCurrentThreadId ( void ) : int
public Thread::getThreadId ( void ) : int
public static Thread::globally ( void ) : mixed
public Thread::isJoined ( void ) : bool
public Thread::isStarted ( void ) : bool
public Thread::join ( void ) : bool
public Thread::kill ( void ) : void
public Thread::start ([ int $options ] ) : bool
}

Spis treści

add a note add a note

User Contributed Notes 1 note

up
-6
event2game at gmail dot com
10 years 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