前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >专栏 >php pthreads多线程的安装与使用

php pthreads多线程的安装与使用

作者头像
超级小可爱
发布2023-02-23 09:48:56
发布2023-02-23 09:48:56
8170
举报
文章被收录于专栏:小孟开发笔记小孟开发笔记

安装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: %s\n", $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: %s\n", $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: %s\n", $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, %s\r\n",$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("%s\n",$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, %s\r\n",$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("%s\n",$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 here\n");<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("%s\n",$sql);<br>}<br>$dbh = null;<br>printf("runtime: %s, %s, %s\n", 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("%s\n",$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,%s\n", $mobile, $id );<br>file\_put\_contents("mobile\_error.log", $error, FILE\_APPEND);<br>}<br>#$dbh = null;<br>printf("runtime: %s, %s, %s, %s\n", date('Y-m-d H:i:s'), $this->worker->getThreadId() ,$mobile, $id);<br>#printf("runtime: %s, %s\n", 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("%s\n",$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多线程的安装与使用

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档