php Pthread 多线程 Worker
程序员文章站
2022-03-18 15:18:15
1 sql = $sql; 13 } 14 15 public function run() 16 { 17 $dbh = $this->worker->getConnection(); 18 $row = $dbh->prepare($this->sql,array(PDO::ATTR_CU... ......
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 /* 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
上一篇: Python Day1
下一篇: 小心你的 ADSL猫被黑