layout: post
php多进程使用
subtitle: pcntl date: 2020-06-02 author: BY header-img: img/post-bg-kuaidi.jpg catalog: true tags: - Xcode - iOS
php多进程使用
编译php开启–enable-pcntl以及–enable-sysvmsg
pcntl 用来创建子进程
sysvmsg 用来进程之间的通讯,消息队列
测试代码
// 直接调用这个方法
public function more_pcntl()
{
$click_info['param'] = [
[
'time' => time(),
'layer' => 'product',
'action' => 'product_type_nine_free_shipping'
],
[
'time' => time(),
'layer' => 'product2',
'action' => 'product_type_nine_free_shipping2'
],
];
$click_info['domain'] = 'xxx.xx.net';
$click_info['platform'] = 'h5';
$ret2 = $this->addData($click_info);
// \var_dump($ret2);
}
# 创建进程以及获取子进程返回的数据
public function addData($info = [])
{
$data = array();
$msg_key = ftok(__FILE__, 'a');
$msg_queue = msg_get_queue($msg_key);
$param = $info['param'] ?? [];
$workers = \count($param); // 进程数量
$pids = array();
foreach ($param as $key => $value) {
for ($i = 0; $i < $workers; $i++) {
$pids[$i] = pcntl_fork();
switch ($pids[$i]) {
case -1:
echo "fork error : {$i} \r\n";
exit;
case 0:
$logic = new Pcn();
$back_data = $logic->getApi($value);
msg_send($msg_queue, 1, $back_data);
exit;
default:
break;
}
}
}
foreach ($pids as $i => $pid) {
if ($pid) {
pcntl_waitpid($pid, $status);
msg_receive($msg_queue, 1, $msg_type, 1024, $msg);
$data[] = $msg;
}
}
msg_remove_queue($msg_queue);
\var_dump($data);
echo '执行ok' . \PHP_EOL;
}
# 耗时操作
class Pcn
{
public function getApi($data = [])
{
// \var_dump($data);
// 耗时
\sleep(2);
return \microtime();
}
}
php 编译
./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