<?php
//Worker是具有持久化上下文(执行环境)的线程对象
//Worker对象start()后,会执行run()方法,run()方法执行完毕,线程也不会消亡
class MySqlWorker extends Worker {private $name = '';private $db = null;public function __construct($name) {$this->name = $name;}public function run() {$this->db = mysql_connect('127.0.0.1', 'root', '');mysql_select_db('test', $this->db);}public function getDb() {return $this->db;}
}//Stackable是Threaded的一个别称,直到pthreads v.2.0.0
class Query extends Threaded {private $sql = '';private $data = array();public function __construct($sql) {$this->sql = $sql;}public function run() {//访问线程工作对象$db = $this->worker->getDb();$res = mysql_query($this->sql, $db);$tmp = array();while($row = mysql_fetch_assoc($res)) {//这里不能使用$this->data[] = $row;这种方式。$tmp[] = $row;}$this->data = $tmp;}public function getData() {return $this->data;}
}$mysqlWork = new MySqlWorker('mysqlWork');
$query1 = new Query('select * from test order by id limit 0,2');
$query2 = new Query('select * from test order by id limit 2,2');//通过Worker的stack方法,我们把对象加入到Worker中
//会激活Worker执行对象的run()方法。
//说白了就是会执行$query1,$query2的run()方法。
$mysqlWork->stack($query1);
$mysqlWork->stack($query2);$mysqlWork->start();
//执行完Worker中的对象后,关闭Worker。
//如果把这段代码放到$query1->getData()和$query2->getData()之后
//则会输出两个空数组,那该方法的作用有可能是等待Worker中对象执行完毕,类似join方法()。
$mysqlWork->shutdown();var_dump($query1->getData());
var_dump($query2->getData());
转载于:https://www.cnblogs.com/jkko123/p/6294596.html