1 <?php 2 //PHP 高级编程之多线程 http://www.netkiller.cn/journal/thread.php.html#idp57489856 3 //worker 是一个具有持久化上下文的线程对象,通常用来在多个线程中使用。 4 //worker 对象start后,会直接运行run()方法,执行完毕之后,线程也不会die掉 5 //SQLQuery 是任务类 6 class SQLQuery extends Thread 7 { 8 public $worker; 9 public $sql; 10 public function __construct($sql) 11 { 12 $this->sql = $sql; 13 } 14 15 public function run() 16 { 17 $dbh = $this->worker->getConnection(); 18 $row = $dbh->prepare($this->sql,array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY)); 19 $row->execute(); 20 while($member = $row->fetch(PDO::FETCH_ASSOC)) 21 { 22 // print_r($member); 23 } 24 } 25 } 26 //worker 执行任务 27 class ExampleWorker extends Worker { 28 public static $dbh; 29 public function __construct($name) { 30 } 31 32 /* 33 * The run method should just prepare the environment for the work that is coming ... 34 */ 35 public function run(){ 36 self::$dbh = new PDO('mysql:dbname=mix;host=192.168.33.11','root',''); 37 } 38 public function getConnection(){ 39 return self::$dbh; 40 } 41 } 42 43 $worker = new ExampleWorker("My Worker Thread"); 44 45 for ($i = 0; $i < 5; ++$i) { 46 $worker->stack(new SQLQuery('select * from stores limit '.$i)); // 将要执行的任务入栈 47 } 48 49 echo "{$worker->getStacked()} tasks\n"; //获取栈中剩余的任务数量 50 $worker->start(); //执行完Worker中的对象后 51 $worker->shutdown(); //关闭Worker。 跟队列很像 52 53 /* 多线程检测服务是否正常案例 https://www.cnblogs.com/zz-952/p/9762284.html 54 这里会报错 55 Uncaught RuntimeException: the creator of ExampleWorker already started 56 没有线程die掉 57 while(true) 58 { 59 sleep(5); 60 $worker->start(); 61 $worker->shutdown(); 62 } 63 */ 64