您好,欢迎访问一九零五行业门户网

php pthreads的使用方法

php pthreads的使用方法:1、通过“pecl install pthreads”安装pthreads;2、在需要控制多个线程同一时刻只能有一个线程工作的情况下使用互斥锁。
本文操作环境:windows7系统、php7.0.2版,dell g3电脑
php多线程pthreads的安装与使用
安装pthreads 基本上需要重新编译php,加上 --enable-maintainer-zts 参数,但是用这个文档很少;bug会很多很有很多意想不到的问题,生成环境上只能呵呵了,所以这个东西玩玩就算了,真正多线程还是用python、c等等
以下代码大部分来自网络
一、安装这里使用的是 php-7.0.2
./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-mysqlmake && make install
安装pthreads
pecl install pthreads
二、thread<?php#1$thread = new class extends thread { public function run() { echo "hello world {$this->getthreadid()}\n"; } };$thread->start() && $thread->join();#2class workerthread extends thread { public function __construct($i){ $this->i=$i; } public function run(){ while(true){ echo $this->i."\n"; sleep(1); } } }for($i=0;$i<50;$i++){ $workers[$i]=new workerthread($i); $workers[$i]->start();}?>
三、 worker 与 stackablestackables are tasks that are executed by worker threads. you can synchronize with, read, and write stackable objects before, after and during their execution.
<?phpclass sqlquery extends stackable { public function __construct($sql) { $this->sql = $sql; } public function run() { $dbh = $this->worker->getconnection(); $row = $dbh->query($this->sql); while($member = $row->fetch(pdo::fetch_assoc)){ print_r($member); } }}class exampleworker extends worker { public static $dbh; public function __construct($name) { } public function run(){ self::$dbh = new pdo('mysql:host=10.0.0.30;dbname=testdb','root','123456'); } public function getconnection(){ return self::$dbh; }}$worker = new exampleworker("my worker thread");$sql1 = new sqlquery('select * from test order by id desc limit 1,5');$worker->stack($sql1);$sql2 = new sqlquery('select * from test order by id desc limit 5,5');$worker->stack($sql2);$worker->start();$worker->shutdown();?>
四、 互斥锁什么情况下会用到互斥锁?在你需要控制多个线程同一时刻只能有一个线程工作的情况下可以使用。一个简单的计数器程序,说明有无互斥锁情况下的不同
<?php$counter = 0;$handle=fopen("/tmp/counter.txt", "w");fwrite($handle, $counter );fclose($handle);class counterthread extends thread { public function __construct($mutex = null){ $this->mutex = $mutex; $this->handle = fopen("/tmp/counter.txt", "w+"); } public function __destruct(){ fclose($this->handle); } public function run() { if($this->mutex) $locked=mutex::lock($this->mutex); $counter = intval(fgets($this->handle)); $counter++; rewind($this->handle); fputs($this->handle, $counter ); printf("thread #%lu says: %s\n", $this->getthreadid(),$counter); if($this->mutex) mutex::unlock($this->mutex); }}//没有互斥锁for ($i=0;$i<50;$i++){ $threads[$i] = new counterthread(); $threads[$i]->start();}//加入互斥锁$mutex = mutex::create(true);for ($i=0;$i<50;$i++){ $threads[$i] = new counterthread($mutex); $threads[$i]->start();}mutex::unlock($mutex);for ($i=0;$i<50;$i++){ $threads[$i]->join();}mutex::destroy($mutex);?>
多线程与共享内存在共享内存的例子中,没有使用任何锁,仍然可能正常工作,可能工作内存操作本身具备锁的功能
<?php$tmp = tempnam(__file__, 'php');$key = ftok($tmp, 'a');$shmid = shm_attach($key);$counter = 0;shm_put_var( $shmid, 1, $counter );class counterthread extends thread { public function __construct($shmid){ $this->shmid = $shmid; } public function run() { $counter = shm_get_var( $this->shmid, 1 ); $counter++; shm_put_var( $this->shmid, 1, $counter ); printf("thread #%lu says: %s\n", $this->getthreadid(),$counter); }}for ($i=0;$i<100;$i++){ $threads[] = new counterthread($shmid);}for ($i=0;$i<100;$i++){ $threads[$i]->start();}for ($i=0;$i<100;$i++){ $threads[$i]->join();}shm_remove( $shmid );shm_detach( $shmid );?>
五、 线程同步有些场景我们不希望 thread->start() 就开始运行程序,而是希望线程等待我们的命令。$thread->wait();测作用是 thread->start()后线程并不会立即运行,只有收到 $thread->notify(); 发出的信号后才运行
<?php$tmp = tempnam(__file__, 'php');$key = ftok($tmp, 'a');$shmid = shm_attach($key);$counter = 0;shm_put_var( $shmid, 1, $counter );class counterthread extends thread { public function __construct($shmid){ $this->shmid = $shmid; } public function run() { $this->synchronized(function($thread){ $thread->wait(); }, $this); $counter = shm_get_var( $this->shmid, 1 ); $counter++; shm_put_var( $this->shmid, 1, $counter ); printf("thread #%lu says: %s\n", $this->getthreadid(),$counter); }}for ($i=0;$i<100;$i++){ $threads[] = new counterthread($shmid);}for ($i=0;$i<100;$i++){ $threads[$i]->start();}for ($i=0;$i<100;$i++){ $threads[$i]->synchronized(function($thread){ $thread->notify(); }, $threads[$i]);}for ($i=0;$i<100;$i++){ $threads[$i]->join();}shm_remove( $shmid );shm_detach( $shmid );?>
六、线程池一个pool类
<?phpclass update extends thread { public $running = false; public $row = array(); public function __construct($row) { $this->row = $row; $this->sql = null; } public function run() { if(strlen($this->row['bankno']) > 100 ){ $bankno = safenet_decrypt($this->row['bankno']); }else{ $error = sprintf("%s, %s\r\n",$this->row['id'], $this->row['bankno']); file_put_contents("bankno_error.log", $error, file_append); } if( strlen($bankno) > 7 ){ $sql = sprintf("update members set bankno = '%s' where id = '%s';", $bankno, $this->row['id']); $this->sql = $sql; } printf("%s\n",$this->sql); }}class pool { public $pool = array(); public function __construct($count) { $this->count = $count; } public function push($row){ if(count($this->pool) < $this->count){ $this->pool[] = new update($row); return true; }else{ return false; } } public function start(){ foreach ( $this->pool as $id => $worker){ $this->pool[$id]->start(); } } public function join(){ foreach ( $this->pool as $id => $worker){ $this->pool[$id]->join(); } } public function clean(){ foreach ( $this->pool as $id => $worker){ if(! $worker->isrunning()){ unset($this->pool[$id]); } } }}try { $dbh = new pdo("mysql:host=" . str_replace(':', ';port=', $dbhost) . ";dbname=$dbname", $dbuser, $dbpw, array( pdo::mysql_attr_init_command => 'set names \'utf8\'', pdo::mysql_attr_compress => true ) ); $sql = "select id,bankno from members order by id desc"; $row = $dbh->query($sql); $pool = new pool(5); while($member = $row->fetch(pdo::fetch_assoc)) { while(true){ if($pool->push($member)){ //压入任务到池中 break; }else{ //如果池已经满,就开始启动线程 $pool->start(); $pool->join(); $pool->clean(); } } } $pool->start(); $pool->join(); $dbh = null;} catch (exception $e) { echo '[' , date('h:i:s') , ']', '系统错误', $e->getmessage(), "\n";}?>
动态队列线程池上面的例子是当线程池满后执行start统一启动,下面的例子是只要线程池中有空闲便立即创建新线程。
<?phpclass update extends thread { public $running = false; public $row = array(); public function __construct($row) { $this->row = $row; $this->sql = null; //print_r($this->row); } public function run() { if(strlen($this->row['bankno']) > 100 ){ $bankno = safenet_decrypt($this->row['bankno']); }else{ $error = sprintf("%s, %s\r\n",$this->row['id'], $this->row['bankno']); file_put_contents("bankno_error.log", $error, file_append); } if( strlen($bankno) > 7 ){ $sql = sprintf("update members set bankno = '%s' where id = '%s';", $bankno, $this->row['id']); $this->sql = $sql; } printf("%s\n",$this->sql); }}try { $dbh = new pdo("mysql:host=" . str_replace(':', ';port=', $dbhost) . ";dbname=$dbname", $dbuser, $dbpw, array( pdo::mysql_attr_init_command => 'set names \'utf8\'', pdo::mysql_attr_compress => true ) ); $sql = "select id,bankno from members order by id desc limit 50"; $row = $dbh->query($sql); $pool = array(); while($member = $row->fetch(pdo::fetch_assoc)) { $id = $member['id']; while (true){ if(count($pool) < 5){ $pool[$id] = new update($member); $pool[$id]->start(); break; }else{ foreach ( $pool as $name => $worker){ if(! $worker->isrunning()){ unset($pool[$name]); } } } } } $dbh = null;} catch (exception $e) { echo '【' , date('h:i:s') , '】', '【系统错误】', $e->getmessage(), "\n";}?> 
pthreads pool类<?phpclass webworker extends worker { public function __construct(safelog $logger) { $this->logger = $logger; } protected $loger;}class webwork extends stackable { public function iscomplete() { return $this->complete; } public function run() { $this->worker ->logger ->log("%s executing in thread #%lu", __class__, $this->worker->getthreadid()); $this->complete = true; } protected $complete;}class safelog extends stackable { protected function log($message, $args = []) { $args = func_get_args(); if (($message = array_shift($args))) { echo vsprintf( "{$message}\n", $args); } }}$pool = new pool(8, \webworker::class, [new safelog()]);$pool->submit($w=new webwork());$pool->submit(new webwork());$pool->submit(new webwork());$pool->submit(new webwork());$pool->submit(new webwork());$pool->submit(new webwork());$pool->submit(new webwork());$pool->submit(new webwork());$pool->submit(new webwork());$pool->submit(new webwork());$pool->submit(new webwork());$pool->submit(new webwork());$pool->submit(new webwork());$pool->submit(new webwork());$pool->shutdown();$pool->collect(function($work){ return $work->iscomplete(); });var_dump($pool);
七、多线程文件安全读写lock_sh 取得共享锁定(读取的程序)
lock_ex 取得独占锁定(写入的程序
lock_un 释放锁定(无论共享或独占)
lock_nb 如果不希望 flock() 在锁定时堵塞
<?php$fp = fopen("/tmp/lock.txt", "r+");if (flock($fp, lock_ex)) { // 进行排它型锁定 ftruncate($fp, 0); // truncate file fwrite($fp, "write something here\n"); fflush($fp); // flush output before releasing the lock flock($fp, lock_un); // 释放锁定} else { echo "couldn't get the lock!";}fclose($fp);$fp = fopen('/tmp/lock.txt', 'r+');if(!flock($fp, lock_ex | lock_nb)) { echo 'unable to obtain lock'; exit(-1);}fclose($fp);?>
八、多线程与数据连接pthreads 与 pdo 同时使用是,需要注意一点,需要静态声明public static $dbh;并且通过单例模式访问数据库连接。
worker 与 pdo<?phpclass work extends stackable { public function __construct() { } public function run() { $dbh = $this->worker->getconnection(); $sql = "select id,name from members order by id desc limit 50"; $row = $dbh->query($sql); while($member = $row->fetch(pdo::fetch_assoc)){ print_r($member); } }}class exampleworker extends worker { public static $dbh; public function __construct($name) { } /* * the run method should just prepare the environment for the work that is coming ... */ public function run(){ self::$dbh = new pdo('mysql:host=192.168.2.1;dbname=example','www','123456'); } public function getconnection(){ return self::$dbh; }}$worker = new exampleworker("my worker thread");$work=new work();$worker->stack($work);$worker->start();$worker->shutdown();?>
pool 与 pdo在线程池中链接数据库
# cat pool.php<?phpclass exampleworker extends worker { public function __construct(logging $logger) { $this->logger = $logger; } protected $logger;}/* the collectable class implements machinery for pool::collect */class work extends stackable { public function __construct($number) { $this->number = $number; } public function run() { $dbhost = 'db.example.com'; // 数据库服务器 $dbuser = 'example.com'; // 数据库用户名 $dbpw = 'password'; // 数据库密码 $dbname = 'example_real'; $dbh = new pdo("mysql:host=$dbhost;port=3306;dbname=$dbname", $dbuser, $dbpw, array( pdo::mysql_attr_init_command => 'set names \'utf8\'', pdo::mysql_attr_compress => true, pdo::attr_persistent => true ) ); $sql = "select open_time, `comment` from mt4_trades where login='".$this->number['name']."' and cmd='6' and `comment` = '".$this->number['order'].":deposit'"; #echo $sql; $row = $dbh->query($sql); $mt4_trades = $row->fetch(pdo::fetch_assoc); if($mt4_trades){ $row = null; $sql = "update db_example.accounts set paystatus='成功', deposit_time='".$mt4_trades['open_time']."' where `order` = '".$this->number['order']."';"; $dbh->query($sql); #printf("%s\n",$sql); } $dbh = null; printf("runtime: %s, %s, %s\n", date('y-m-d h:i:s'), $this->worker->getthreadid() ,$this->number['order']); }}class logging extends stackable { protected static $dbh; public function __construct() { $dbhost = 'db.example.com'; // 数据库服务器 $dbuser = 'example.com'; // 数据库用户名 $dbpw = 'password'; // 数据库密码 $dbname = 'example_real'; // 数据库名 self::$dbh = new pdo("mysql:host=$dbhost;port=3306;dbname=$dbname", $dbuser, $dbpw, array( pdo::mysql_attr_init_command => 'set names \'utf8\'', pdo::mysql_attr_compress => true ) ); } protected function log($message, $args = []) { $args = func_get_args(); if (($message = array_shift($args))) { echo vsprintf("{$message}\n", $args); } } protected function getconnection(){ return self::$dbh; }}$pool = new pool(200, \exampleworker::class, [new logging()]);$dbhost = 'db.example.com'; // 数据库服务器$dbuser = 'example.com'; // 数据库用户名$dbpw = 'password'; // 数据库密码$dbname = 'db_example';$dbh = new pdo("mysql:host=$dbhost;port=3306;dbname=$dbname", $dbuser, $dbpw, array( pdo::mysql_attr_init_command => 'set names \'utf8\'', pdo::mysql_attr_compress => true ) );$sql = "select `order`,name from accounts where deposit_time is null order by id desc";$row = $dbh->query($sql);while($account = $row->fetch(pdo::fetch_assoc)){ $pool->submit(new work($account));}$pool->shutdown();?> 
进一步改进上面程序,我们使用单例模式 $this->worker->getinstance(); 全局仅仅做一次数据库连接,线程使用共享的数据库连接
<?phpclass exampleworker extends worker { #public function __construct(logging $logger) { # $this->logger = $logger; #} #protected $logger; protected static $dbh; public function __construct() { } public function run(){ $dbhost = 'db.example.com'; // 数据库服务器 $dbuser = 'example.com'; // 数据库用户名 $dbpw = 'password'; // 数据库密码 $dbname = 'example'; // 数据库名 self::$dbh = new pdo("mysql:host=$dbhost;port=3306;dbname=$dbname", $dbuser, $dbpw, array( pdo::mysql_attr_init_command => 'set names \'utf8\'', pdo::mysql_attr_compress => true, pdo::attr_persistent => true ) ); } protected function getinstance(){ return self::$dbh; }}/* the collectable class implements machinery for pool::collect */class work extends stackable { public function __construct($data) { $this->data = $data; #print_r($data); } public function run() { #$this->worker->logger->log("%s executing in thread #%lu", __class__, $this->worker->getthreadid() ); try { $dbh = $this->worker->getinstance(); #print_r($dbh); $id = $this->data['id']; $mobile = safenet_decrypt($this->data['mobile']); #printf("%d, %s \n", $id, $mobile); if(strlen($mobile) > 11){ $mobile = substr($mobile, -11); } if($mobile == 'null'){ # $sql = "update members_digest set mobile = '".$mobile."' where id = '".$id."'"; # printf("%s\n",$sql); # $dbh->query($sql); $mobile = ''; $sql = "update members_digest set mobile = :mobile where id = :id"; }else{ $sql = "update members_digest set mobile = md5(:mobile) where id = :id"; } $sth = $dbh->prepare($sql); $sth->bindvalue(':mobile', $mobile); $sth->bindvalue(':id', $id); $sth->execute(); #echo $sth->debugdumpparams(); } catch(pdoexception $e) { $error = sprintf("%s,%s\n", $mobile, $id ); file_put_contents("mobile_error.log", $error, file_append); } #$dbh = null; printf("runtime: %s, %s, %s, %s\n", date('y-m-d h:i:s'), $this->worker->getthreadid() ,$mobile, $id); #printf("runtime: %s, %s\n", date('y-m-d h:i:s'), $this->number); }}$pool = new pool(100, \exampleworker::class, []);#foreach (range(0, 100) as $number) {# $pool->submit(new work($number));#}$dbhost = 'db.example.com'; // 数据库服务器$dbuser = 'example.com'; // 数据库用户名$dbpw = 'password'; // 数据库密码$dbname = 'example';$dbh = new pdo("mysql:host=$dbhost;port=3307;dbname=$dbname", $dbuser, $dbpw, array( pdo::mysql_attr_init_command => 'set names \'utf8\'', pdo::mysql_attr_compress => true ) );#print_r($dbh);#$sql = "select id, mobile from members where id < :id";#$sth = $dbh->prepare($sql);#$sth->bindvalue(':id',300);#$sth->execute();#$result = $sth->fetchall();#print_r($result);##$sql = "update members_digest set mobile = :mobile where id = :id";#$sth = $dbh->prepare($sql);#$sth->bindvalue(':mobile', 'aa');#$sth->bindvalue(':id','272');#echo $sth->execute();#echo $sth->querystring;#echo $sth->debugdumpparams();$sql = "select id, mobile from members order by id asc"; // limit 1000";$row = $dbh->query($sql);while($members = $row->fetch(pdo::fetch_assoc)){ #$order = $account['order']; #printf("%s\n",$order); //print_r($members); $pool->submit(new work($members)); #unset($account['order']);}$pool->shutdown();?>
多线程中操作数据库总结总的来说 pthreads 仍然处在发展中,仍有一些不足的地方,我们也可以看到pthreads的git在不断改进这个项目
数据库持久链接很重要,否则每个线程都会开启一次数据库连接,然后关闭,会导致很多链接超时。
<?php$dbh = new pdo('mysql:host=localhost;dbname=test', $user, $pass, array( pdo::attr_persistent => true));?>
推荐学习:《php视频教程》
以上就是php pthreads的使用方法的详细内容。
其它类似信息

推荐信息