php 多线程扩展 pthreads 安装 及 使用
1、扩展的编译安装php(Linux),编辑参数 --enable-maintainer-zts 是必选项:
2、下载 php7:
http://tw2.php.net/get/php-7.1.2.tar.gz/from/a/mirrorduoxc
3、解压并编译php
tar -zxf php-7.1.2.tar.gz
cd php-7.1.2
./configure --prefix=/usr/local/php712 --with-config-file-path=/usr/local/php712/etc --with-config-file-scan-dir=/usr/local/php712/etc/php.d --with-mcrypt=/usr/include --enable-mysqlnd --with-mysqli --with-pdo-mysql --enable-fpm --with-gd --with-iconv --with-zlib --enable-xml --enable-shmop --enable-sysvsem --enable-inline-optimization --enable-mbregex --enable-mbstring --enable-ftp --enable-gd-native-ttf --enable-pcntl --enable-sockets --with-xmlrpc --enable-zip --enable-soap --without-pear --enable-session --with-curl --with-jpeg-dir --enable-sqlite-utf8 --enable-sysvmsg --enable-sysvshm --enable-wddx --with-xsl --enable-opcache --enable-maintainer-zts
sudo make -j8 && sudo make install
4、php编译完之后开始编译安装 pthreads扩展
5、下载pthreads扩展
https://github.com/krakjoe/pthreads
6、解压并安装
tar -zxf pthreads-3.1.6.tgz
cd pthreads-3.1.6
./configure --with-php-config=/usr/local/php712/bin/php-config
sudo make -j8 && sudo make install
7、配置php.ini
sudo vim /usr/local/php712/etc/php.ini
在 php.ini 最后添加:
[pthreads]
extension=pthreads.so
8、测试pthreads扩展
Thread.php :
<?php
Class Thread {
public $hooks = array();
public $args = array();
public function thread() {
}
public function addthread($func) {
$args = array_slice(func_get_args(), 1);
$this->hooks[] = $func;
$this->args[] = $args;
return true;
}
public function runthread() {
if(isset($_GET['flag'])) {
$flag = intval($_GET['flag']);
}
if($flag || $flag === 0) {
call_user_func_array($this->hooks[$flag], $this->args[$flag]);
} else {
for($i = 0, $size = count($this->hooks); $i < $size; $i++) {
$fp=fsockopen($_SERVER['HTTP_HOST'],$_SERVER['SERVER_PORT']);
if($fp) {
$out = "GET {$_SERVER['PHP_SELF']}?flag=$i HTTP/1.1rn";
$out .= "Host: {$_SERVER['HTTP_HOST']}rn";
$out .= "Connection: Closernrn";
fputs($fp,$out);
fclose($fp);
}
}
}
}
}
test.php :
include('Thread.php');
Class AsyncOperation extends Thread {
public function __construct($arg){
$this->arg = $arg;
}
public function run(){
if($this->arg){
printf("Hello %s\n", $this->arg);
}
}
}
$thread = new AsyncOperation("World");
if($thread->start()){
$thread->join();
}