CakeFest 2024: The Official CakePHP Conference

Worker クラス

(PECL pthreads >= 2.0.0)

はじめに

ワーカースレッドには永続コンテキストがあり、たいていの場合はスレッドに対して使えます。

ワーカーを開始させると run メソッドを実行しますが、以下のいずれかの条件を満たすまでスレッドは終了しません。

  • Worker がスコープから外れる (どこからも参照されなくなる)

  • プログラマーが shutdown を呼ぶ

  • スクリプトが終了する

つまり、プログラマーは実行中のコンテキストを再利用できるということです。 オブジェクトを Worker のスタックに置くと、そのオブジェクトの run メソッドを Worker が実行します。

クラス概要

class Worker extends Thread implements Traversable, Countable, ArrayAccess {
/* メソッド */
public collect(Callable $collector = ?): int
public getStacked(): int
public isShutdown(): bool
public shutdown(): bool
public stack(Threaded &$work): int
public unstack(): int
/* 継承したメソッド */
public Thread::join(): bool
public Thread::start(int $options = ?): bool
}

目次

add a note

User Contributed Notes 1 note

up
-8
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