layout: post
php多线程使用
subtitle: php多线程使用 date: 2020-06-02 author: BY header-img: img/post-bg-kuaidi.jpg catalog: true tags: - java - springboot - thymeleaf
php多线程使用
按照要求编译php,以及安装该扩展,值得注意的是 v3+ 版本不支持fpm只支持cli
Requirements
PHP 7.2+
ZTS Enabled ( Thread Safety )
Posix Threads Implementation
Testing has been carried out on x86, x64 and ARM, in general you just need a compiler and pthread.h
测试文件
# 调用方法
/**
* 多线程直接测试
* /usr/local/php7/bin/php think util pthreads
* @param string $opt
* @return void
* @copyright
* @author lxx
*/
public function pthreads($opt = '')
{
$back_data = [];
$threads['get_a'] = new GetApi('a');
$threads['get_b'] = new GetApi('b');
foreach ($threads as $thread) {
// echo '$thread->start()' . PHP_EOL;
$thread->start(); // 开始执行线程
// echo '$thread->startend()' . PHP_EOL;
}
// foreach($threads as $thread) {
// $thread->join(); // 等待线程
// }
// 一直等待
while (true) {
$is_back = 0;
foreach ($threads as $key => $thread) {
if ($thread->data != null) {
$is_back = $is_back + 1;
$back_data[$key] = $thread->data;
}
}
if ($is_back == \count($threads)) {
break;
}
}
echo '执行结果' . PHP_EOL;
var_dump($back_data);
return true;
}
# 类文件
/**
* 调用api测试
*
* @copyright
* @author lxx
*/
class GetApi extends \Thread
{
public $data = null;
public function __construct($arg)
{
$this->arg = $arg;
}
// 当调用start方法时,该对象的run方法中的代码将在独立线程中异步执行。
public function run()
{
if ($this->arg) {
// 耗时的操作
sleep(1);
$this->data = $this->arg;
}
}
}
编译的时候注意
./configure \
--prefix=/usr/local/php7 \
--exec-prefix=/usr/local/php7 \
--bindir=/usr/local/php7/bin \
--sbindir=/usr/local/php7/sbin \
--includedir=/usr/local/php7/include \
--libdir=/usr/local/php7/lib/php \
--mandir=/usr/local/php7/php/man \
--with-config-file-path=/usr/local/php7/etc \
--with-mysql-sock=/usr/local/mysql/mysql.sock \
--with-mcrypt=/usr/include \
--with-mhash \
--with-openssl \
--with-mysql=shared,mysqlnd \
--with-mysqli=shared,mysqlnd \
--with-pdo-mysql=shared,mysqlnd \
--with-gd \
--with-iconv \
--with-zlib \
--enable-zip \
--enable-inline-optimization \
--disable-debug \
--disable-rpath \
--enable-shared \
--enable-xml \
--enable-bcmath \
--enable-shmop \
--enable-sysvsem \
--enable-mbregex \
--enable-mbstring \
--enable-ftp \
--enable-gd-native-ttf \
--enable-pcntl \
--enable-sockets \
--with-xmlrpc \
--enable-soap \
--without-pear \
--with-gettext \
--enable-session \
--with-curl \
--with-jpeg-dir \
--with-freetype-dir \
--enable-opcache \
--enable-redis \
--enable-fpm \
--enable-fastcgi \
--with-fpm-user=www \
--with-fpm-group=www \
--without-gdbm \
--disable-fileinfo \
--enable-sysvmsg \
--enable-maintainer-zts