安装Pthreads 基本上需要重新编译PHP,加上 –enable-maintainer-zts 参数,但是用这个文档很少;bug会很多很有很多意想不到的问题,生成环境上只能呵呵了,所以这个东西玩玩就算了,真正多线程还是用Python、C等等
一、安装
这里使用的是 php-7.0.2
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | ./configure --prefix=/usr/local/php7 --with-config-file-path=/etc --with-config-file-scan-dir=/etc/php.d --enable-debug --enable-maintainer-zts --enable-pcntl --enable-fpm --enable-opcache --enable-embed=shared --enable-json=shared --enable-phpdbg --with-curl=shared --with-mysql=/usr/local/mysql --with-mysqli=/usr/local/mysql/bin/mysql_config --with-pdo-mysql |
---|
make && make install
安装pthreads
pecl install pthreads
二、Thread
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | <?php<br>#1<br>$thread = new class extends Thread {<br>public function run() {<br>echo "Hello World {$this->getThreadId()}n"; <br>} <br>};<br>$thread->start() && $thread->join();<br>#2<br>class workerThread extends Thread { <br>public function __construct($i){<br>$this->i=$i;<br>}<br>public function run(){<br>while(true){<br>echo $this->i."n";<br>sleep(1);<br>} <br>} <br>}<br>for($i=0;$i<50;$i ){<br>$workers[$i]=new workerThread($i);<br>$workers[$i]->start();<br>}<br>?> |
---|
三、 Worker 与 Stackable
Stackables are tasks that are executed by Worker threads. You can synchronize with, read, and write Stackable objects before, after and during their execution.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | <?php<br>class SQLQuery extends Stackable {<br>public function __construct($sql) {<br>$this->sql = $sql;<br>}<br>public function run() {<br>$dbh = $this->worker->getConnection();<br>$row = $dbh->query($this->sql);<br>while($member = $row->fetch(PDO::FETCH_ASSOC)){<br>print_r($member);<br>}<br>}<br>}<br>class ExampleWorker extends Worker {<br>public static $dbh;<br>public function __construct($name) {<br>}<br>public function run(){<br>self::$dbh = new PDO('mysql:host=10.0.0.30;dbname=testdb','root','123456');<br>}<br>public function getConnection(){<br>return self::$dbh;<br>}<br>}<br>$worker = new ExampleWorker("My Worker Thread");<br>$sql1 = new SQLQuery('select * from test order by id desc limit 1,5');<br>$worker->stack($sql1);<br>$sql2 = new SQLQuery('select * from test order by id desc limit 5,5');<br>$worker->stack($sql2);<br>$worker->start();<br>$worker->shutdown();<br>?> |
---|
四、 互斥锁
什么情况下会用到互斥锁?在你需要控制多个线程同一时刻只能有一个线程工作的情况下可以使用。一个简单的计数器程序,说明有无互斥锁情况下的不同
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | <?php<br>$counter = 0;<br>$handle=fopen("/tmp/counter.txt", "w");<br>fwrite($handle, $counter );<br>fclose($handle);<br>class CounterThread extends Thread {<br>public function __construct($mutex = null){<br>$this->mutex = $mutex;<br>$this->handle = fopen("/tmp/counter.txt", "w ");<br>}<br>public function __destruct(){<br>fclose($this->handle);<br>}<br>public function run() {<br>if($this->mutex)<br>$locked=Mutex::lock($this->mutex);<br>$counter = intval(fgets($this->handle));<br>$counter ;<br>rewind($this->handle);<br>fputs($this->handle, $counter );<br>printf("Thread #%lu says: %sn", $this->getThreadId(),$counter);<br>if($this->mutex)<br>Mutex::unlock($this->mutex);<br>}<br>}<br>//没有互斥锁<br>for ($i=0;$i<50;$i ){<br>$threads[$i] = new CounterThread();<br>$threads[$i]->start();<br>}<br>//加入互斥锁<br>$mutex = Mutex::create(true);<br>for ($i=0;$i<50;$i ){<br>$threads[$i] = new CounterThread($mutex);<br>$threads[$i]->start();<br>}<br>Mutex::unlock($mutex);<br>for ($i=0;$i<50;$i ){<br>$threads[$i]->join();<br>}<br>Mutex::destroy($mutex);<br>?> |
---|
多线程与共享内存
在共享内存的例子中,没有使用任何锁,仍然可能正常工作,可能工作内存操作本身具备锁的功能
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | <?php<br>$tmp = tempnam(__FILE__, 'PHP');<br>$key = ftok($tmp, 'a');<br>$shmid = shm_attach($key);<br>$counter = 0;<br>shm_put_var( $shmid, 1, $counter );<br>class CounterThread extends Thread {<br>public function __construct($shmid){<br>$this->shmid = $shmid;<br>}<br>public function run() {<br>$counter = shm_get_var( $this->shmid, 1 );<br>$counter ;<br>shm_put_var( $this->shmid, 1, $counter );<br>printf("Thread #%lu says: %sn", $this->getThreadId(),$counter);<br>}<br>}<br>for ($i=0;$i<100;$i ){<br>$threads[] = new CounterThread($shmid);<br>}<br>for ($i=0;$i<100;$i ){<br>$threads[$i]->start();<br>}<br>for ($i=0;$i<100;$i ){<br>$threads[$i]->join();<br>}<br>shm_remove( $shmid );<br>shm_detach( $shmid );<br>?> |
---|
五、 线程同步
有些场景我们不希望 thread->start() 就开始运行程序,而是希望线程等待我们的命令。thread−>wait();测作用是thread−>start()后线程并不会立即运行,只有收到 thread->notify(); 发出的信号后才运行
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | <?php<br>$tmp = tempnam(__FILE__, 'PHP');<br>$key = ftok($tmp, 'a');<br>$shmid = shm_attach($key);<br>$counter = 0;<br>shm_put_var( $shmid, 1, $counter );<br>class CounterThread extends Thread {<br>public function __construct($shmid){<br>$this->shmid = $shmid;<br>}<br>public function run() {<br>$this->synchronized(function($thread){<br>$thread->wait();<br>}, $this);<br>$counter = shm_get_var( $this->shmid, 1 );<br>$counter ;<br>shm_put_var( $this->shmid, 1, $counter );<br>printf("Thread #%lu says: %sn", $this->getThreadId(),$counter);<br>}<br>}<br>for ($i=0;$i<100;$i ){<br>$threads[] = new CounterThread($shmid);<br>}<br>for ($i=0;$i<100;$i ){<br>$threads[$i]->start();<br>}<br>for ($i=0;$i<100;$i ){<br>$threads[$i]->synchronized(function($thread){<br>$thread->notify();<br>}, $threads[$i]);<br>}<br>for ($i=0;$i<100;$i ){<br>$threads[$i]->join();<br>}<br>shm_remove( $shmid );<br>shm_detach( $shmid );<br>?> |
---|
六、线程池
一个Pool类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 | <?php<br>class Update extends Thread {<br>public $running = false;<br>public $row = array();<br>public function __construct($row) {<br>$this->row = $row;<br>$this->sql = null;<br>}<br>public function run() {<br>if(strlen($this->row['bankno']) > 100 ){<br>$bankno = safenet_decrypt($this->row['bankno']);<br>}else{<br>$error = sprintf("%s, %srn",$this->row['id'], $this->row['bankno']);<br>file_put_contents("bankno_error.log", $error, FILE_APPEND);<br>}<br>if( strlen($bankno) > 7 ){<br>$sql = sprintf("update members set bankno = '%s' where id = '%s';", $bankno, $this->row['id']);<br>$this->sql = $sql;<br>}<br>printf("%sn",$this->sql);<br>}<br>}<br>class Pool {<br>public $pool = array();<br>public function __construct($count) {<br>$this->count = $count;<br>}<br>public function push($row){<br>if(count($this->pool) < $this->count){<br>$this->pool[] = new Update($row);<br>return true;<br>}else{<br>return false;<br>}<br>}<br>public function start(){<br>foreach ( $this->pool as $id => $worker){<br>$this->pool[$id]->start();<br>}<br>}<br>public function join(){<br>foreach ( $this->pool as $id => $worker){<br>$this->pool[$id]->join();<br>}<br>}<br>public function clean(){<br>foreach ( $this->pool as $id => $worker){<br>if(! $worker->isRunning()){<br>unset($this->pool[$id]);<br>}<br>}<br>}<br>}<br>try {<br>$dbh = new PDO("mysql:host=" . str_replace(':', ';port=', $dbhost) . ";dbname=$dbname", $dbuser, $dbpw, array(<br>PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES 'UTF8'',<br>PDO::MYSQL_ATTR_COMPRESS => true<br>)<br>);<br>$sql = "select id,bankno from members order by id desc";<br>$row = $dbh->query($sql);<br>$pool = new Pool(5);<br>while($member = $row->fetch(PDO::FETCH_ASSOC))<br>{<br>while(true){<br>if($pool->push($member)){ //压入任务到池中<br>break;<br>}else{ //如果池已经满,就开始启动线程<br>$pool->start();<br>$pool->join();<br>$pool->clean();<br>}<br>}<br>}<br>$pool->start();<br>$pool->join();<br>$dbh = null;<br>} catch (Exception $e) {<br>echo '[' , date('H:i:s') , ']', '系统错误', $e->getMessage(), "n";<br>}<br>?> |
---|
动态队列线程池
上面的例子是当线程池满后执行start统一启动,下面的例子是只要线程池中有空闲便立即创建新线程。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 | <?php<br>class Update extends Thread {<br>public $running = false;<br>public $row = array();<br>public function __construct($row) {<br>$this->row = $row;<br>$this->sql = null;<br>//print_r($this->row);<br>}<br>public function run() {<br>if(strlen($this->row['bankno']) > 100 ){<br>$bankno = safenet_decrypt($this->row['bankno']);<br>}else{<br>$error = sprintf("%s, %srn",$this->row['id'], $this->row['bankno']);<br>file_put_contents("bankno_error.log", $error, FILE_APPEND);<br>}<br>if( strlen($bankno) > 7 ){<br>$sql = sprintf("update members set bankno = '%s' where id = '%s';", $bankno, $this->row['id']);<br>$this->sql = $sql;<br>}<br>printf("%sn",$this->sql);<br>}<br>}<br>try {<br>$dbh = new PDO("mysql:host=" . str_replace(':', ';port=', $dbhost) . ";dbname=$dbname", $dbuser, $dbpw, array(<br>PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES 'UTF8'',<br>PDO::MYSQL_ATTR_COMPRESS => true<br>)<br>);<br>$sql = "select id,bankno from members order by id desc limit 50";<br>$row = $dbh->query($sql);<br>$pool = array();<br>while($member = $row->fetch(PDO::FETCH_ASSOC))<br>{<br>$id = $member['id'];<br>while (true){<br>if(count($pool) < 5){<br>$pool[$id] = new Update($member);<br>$pool[$id]->start();<br>break;<br>}else{<br>foreach ( $pool as $name => $worker){<br>if(! $worker->isRunning()){<br>unset($pool[$name]);<br>}<br>}<br>}<br>}<br>}<br>$dbh = null;<br>} catch (Exception $e) {<br>echo '【' , date('H:i:s') , '】', '【系统错误】', $e->getMessage(), "n";<br>}<br>?> |
---|
pthreads Pool类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | <?php<br>class WebWorker extends Worker {<br>public function __construct(SafeLog $logger) {<br>$this->logger = $logger;<br>}<br>protected $loger;<br>}<br>class WebWork extends Stackable {<br>public function isComplete() {<br>return $this->complete;<br>}<br>public function run() {<br>$this->worker<br>->logger<br>->log("%s executing in Thread #%lu",<br>__CLASS__, $this->worker->getThreadId());<br>$this->complete = true;<br>}<br>protected $complete;<br>}<br>class SafeLog extends Stackable {<br>protected function log($message, $args = []) {<br>$args = func_get_args();<br>if (($message = array_shift($args))) {<br>echo vsprintf(<br>"{$message}n", $args);<br>}<br>}<br>}<br>$pool = new Pool(8, WebWorker::class, [new SafeLog()]);<br>$pool->submit($w=new WebWork());<br>$pool->submit(new WebWork());<br>$pool->submit(new WebWork());<br>$pool->submit(new WebWork());<br>$pool->submit(new WebWork());<br>$pool->submit(new WebWork());<br>$pool->submit(new WebWork());<br>$pool->submit(new WebWork());<br>$pool->submit(new WebWork());<br>$pool->submit(new WebWork());<br>$pool->submit(new WebWork());<br>$pool->submit(new WebWork());<br>$pool->submit(new WebWork());<br>$pool->submit(new WebWork());<br>$pool->shutdown();<br>$pool->collect(function($work){<br>return $work->isComplete();<br>});<br>var_dump($pool); |
---|
七、多线程文件安全读写
LOCK_SH 取得共享锁定(读取的程序)
LOCK_EX 取得独占锁定(写入的程序
LOCK_UN 释放锁定(无论共享或独占)
LOCK_NB 如果不希望 flock() 在锁定时堵塞
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | <?php<br>$fp = fopen("/tmp/lock.txt", "r ");<br>if (flock($fp, LOCK_EX)) { // 进行排它型锁定<br>ftruncate($fp, 0); // truncate file<br>fwrite($fp, "Write something heren");<br>fflush($fp); // flush output before releasing the lock<br>flock($fp, LOCK_UN); // 释放锁定<br>} else {<br>echo "Couldn't get the lock!";<br>}<br>fclose($fp);<br>$fp = fopen('/tmp/lock.txt', 'r ');<br>if(!flock($fp, LOCK_EX | LOCK_NB)) {<br>echo 'Unable to obtain lock';<br>exit(-1);<br>}<br>fclose($fp);<br>?> |
---|
八、多线程与数据连接
pthreads 与 pdo 同时使用是,需要注意一点,需要静态声明public static $dbh;并且通过单例模式访问数据库连接。
Worker 与 PDO
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | <?php<br>class Work extends Stackable {<br>public function __construct() {<br>}<br>public function run() {<br>$dbh = $this->worker->getConnection();<br>$sql = "select id,name from members order by id desc limit ";<br>$row = $dbh->query($sql);<br>while($member = $row->fetch(PDO::FETCH_ASSOC)){<br>print_r($member);<br>}<br>}<br>}<br>class ExampleWorker extends Worker {<br>public static $dbh;<br>public function __construct($name) {<br>}<br>/*<br>* The run method should just prepare the environment for the work that is coming ...<br>*/<br>public function run(){<br>self::$dbh = new PDO('mysql:host=...;dbname=example','www','');<br>}<br>public function getConnection(){<br>return self::$dbh;<br>}<br>}<br>$worker = new ExampleWorker("My Worker Thread");<br>$work=new Work();<br>$worker->stack($work);<br>$worker->start();<br>$worker->shutdown();<br>?> |
---|
Pool 与 PDO
在线程池中链接数据库
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 | cat pool.php <?php<br>class ExampleWorker extends Worker {<br>public function __construct(Logging $logger) {<br>$this->logger = $logger;<br>}<br>protected $logger;<br>}<br>/* the collectable class implements machinery for Pool::collect */<br>class Work extends Stackable {<br>public function __construct($number) {<br>$this->number = $number;<br>}<br>public function run() {<br>$dbhost = 'db.example.com'; // 数据库服务器<br>$dbuser = 'example.com'; // 数据库用户名<br>$dbpw = 'password'; // 数据库密码<br>$dbname = 'example_real';<br>$dbh = new PDO("mysql:host=$dbhost;port=;dbname=$dbname", $dbuser, $dbpw, array(<br>PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES 'UTF'',<br>PDO::MYSQL_ATTR_COMPRESS => true,<br>PDO::ATTR_PERSISTENT => true<br>)<br>);<br>$sql = "select OPEN_TIME, `COMMENT` from MT_TRADES where LOGIN='".$this->number['name']."' and CMD='' and `COMMENT` = '".$this->number['order'].":DEPOSIT'";<br>#echo $sql;<br>$row = $dbh->query($sql);<br>$mt_trades = $row->fetch(PDO::FETCH_ASSOC);<br>if($mt_trades){<br>$row = null;<br>$sql = "UPDATE db_example.accounts SET paystatus='成功', deposit_time='".$mt_trades['OPEN_TIME']."' where `order` = '".$this->number['order']."';";<br>$dbh->query($sql);<br>#printf("%sn",$sql);<br>}<br>$dbh = null;<br>printf("runtime: %s, %s, %sn", date('Y-m-d H:i:s'), $this->worker->getThreadId() ,$this->number['order']);<br>}<br>}<br>class Logging extends Stackable {<br>protected static $dbh;<br>public function __construct() {<br>$dbhost = 'db.example.com'; // 数据库服务器<br>$dbuser = 'example.com'; // 数据库用户名<br>$dbpw = 'password'; // 数据库密码<br>$dbname = 'example_real'; // 数据库名<br>self::$dbh = new PDO("mysql:host=$dbhost;port=;dbname=$dbname", $dbuser, $dbpw, array(<br>PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES 'UTF'',<br>PDO::MYSQL_ATTR_COMPRESS => true<br>)<br>);<br>}<br>protected function log($message, $args = []) {<br>$args = func_get_args();<br>if (($message = array_shift($args))) {<br>echo vsprintf("{$message}n", $args);<br>}<br>}<br>protected function getConnection(){<br>return self::$dbh;<br>}<br>}<br>$pool = new Pool(, ExampleWorker::class, [new Logging()]);<br>$dbhost = 'db.example.com'; // 数据库服务器<br>$dbuser = 'example.com'; // 数据库用户名<br>$dbpw = 'password'; // 数据库密码<br>$dbname = 'db_example';<br>$dbh = new PDO("mysql:host=$dbhost;port=;dbname=$dbname", $dbuser, $dbpw, array(<br>PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES 'UTF'',<br>PDO::MYSQL_ATTR_COMPRESS => true<br>)<br>);<br>$sql = "select `order`,name from accounts where deposit_time is null order by id desc";<br>$row = $dbh->query($sql);<br>while($account = $row->fetch(PDO::FETCH_ASSOC))<br>{<br>$pool->submit(new Work($account));<br>}<br>$pool->shutdown();<br>?> |
---|
进一步改进上面程序,我们使用单例模式 $this->worker->getInstance(); 全局仅仅做一次数据库连接,线程使用共享的数据库连接
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 | <?php<br>class ExampleWorker extends Worker {<br>#public function __construct(Logging $logger) {<br># $this->logger = $logger;<br>#}<br>#protected $logger;<br>protected static $dbh;<br>public function __construct() {<br>}<br>public function run(){<br>$dbhost = 'db.example.com'; // 数据库服务器<br>$dbuser = 'example.com'; // 数据库用户名<br>$dbpw = 'password'; // 数据库密码<br>$dbname = 'example'; // 数据库名<br>self::$dbh = new PDO("mysql:host=$dbhost;port=;dbname=$dbname", $dbuser, $dbpw, array(<br>PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES 'UTF'',<br>PDO::MYSQL_ATTR_COMPRESS => true,<br>PDO::ATTR_PERSISTENT => true<br>)<br>);<br>}<br>protected function getInstance(){<br>return self::$dbh;<br>}<br>}<br>/* the collectable class implements machinery for Pool::collect */<br>class Work extends Stackable {<br>public function __construct($data) {<br>$this->data = $data;<br>#print_r($data);<br>}<br>public function run() {<br>#$this->worker->logger->log("%s executing in Thread #%lu", __CLASS__, $this->worker->getThreadId() );<br>try {<br>$dbh = $this->worker->getInstance();<br>#print_r($dbh);<br>$id = $this->data['id'];<br>$mobile = safenet_decrypt($this->data['mobile']);<br>#printf("%d, %s n", $id, $mobile);<br>if(strlen($mobile) > ){<br>$mobile = substr($mobile, -);<br>}<br>if($mobile == 'null'){<br># $sql = "UPDATE members_digest SET mobile = '".$mobile."' where id = '".$id."'";<br># printf("%sn",$sql);<br># $dbh->query($sql);<br>$mobile = '';<br>$sql = "UPDATE members_digest SET mobile = :mobile where id = :id";<br>}else{<br>$sql = "UPDATE members_digest SET mobile = md(:mobile) where id = :id";<br>}<br>$sth = $dbh->prepare($sql);<br>$sth->bindValue(':mobile', $mobile);<br>$sth->bindValue(':id', $id);<br>$sth->execute();<br>#echo $sth->debugDumpParams();<br>}<br>catch(PDOException $e) {<br>$error = sprintf("%s,%sn", $mobile, $id );<br>file_put_contents("mobile_error.log", $error, FILE_APPEND);<br>}<br>#$dbh = null;<br>printf("runtime: %s, %s, %s, %sn", date('Y-m-d H:i:s'), $this->worker->getThreadId() ,$mobile, $id);<br>#printf("runtime: %s, %sn", date('Y-m-d H:i:s'), $this->number);<br>}<br>}<br>$pool = new Pool(, ExampleWorker::class, []);<br>#foreach (range(, ) as $number) {<br># $pool->submit(new Work($number));<br>#}<br>$dbhost = 'db.example.com'; // 数据库服务器<br>$dbuser = 'example.com'; // 数据库用户名<br>$dbpw = 'password'; // 数据库密码<br>$dbname = 'example';<br>$dbh = new PDO("mysql:host=$dbhost;port=;dbname=$dbname", $dbuser, $dbpw, array(<br>PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES 'UTF'',<br>PDO::MYSQL_ATTR_COMPRESS => true<br>)<br>);<br>#print_r($dbh);<br>#$sql = "select id, mobile from members where id < :id";<br>#$sth = $dbh->prepare($sql);<br>#$sth->bindValue(':id',);<br>#$sth->execute();<br>#$result = $sth->fetchAll();<br>#print_r($result);<br>#<br>#$sql = "UPDATE members_digest SET mobile = :mobile where id = :id";<br>#$sth = $dbh->prepare($sql);<br>#$sth->bindValue(':mobile', 'aa');<br>#$sth->bindValue(':id','');<br>#echo $sth->execute();<br>#echo $sth->queryString;<br>#echo $sth->debugDumpParams();<br>$sql = "select id, mobile from members order by id asc"; // limit ";<br>$row = $dbh->query($sql);<br>while($members = $row->fetch(PDO::FETCH_ASSOC))<br>{<br>#$order = $account['order'];<br>#printf("%sn",$order);<br>//print_r($members);<br>$pool->submit(new Work($members));<br>#unset($account['order']);<br>}<br>$pool->shutdown();<br>?> |
---|
多线程中操作数据库总结
总的来说 pthreads 仍然处在发展中,仍有一些不足的地方,我们也可以看到pthreads的git在不断改进这个项目
数据库持久链接很重要,否则每个线程都会开启一次数据库连接,然后关闭,会导致很多链接超时。
1 2 3 4 5 | <?php<br>$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass, array(<br>PDO::ATTR_PERSISTENT => true<br>));<br>?> |
---|
关于php pthreads多线程的安装与使用的相关知识,就先给大家介绍到这里,后续还会持续更新
未经允许不得转载:肥猫博客 » php pthreads多线程的安装与使用