pcntl_fork
<?php
// 进程信号可以不发送,目前来看,子进程执行完毕,回自动关闭主进程
class TestController
{
public function start()
{
echo("top pid:".posix_getpid()); // 获取进程id
$pid = pcntl_fork(); // fork一个新的进程
// echo("child pid $pid");
// // 接收子进程信号
// pcntl_signal(SIGQUIT,function($signo){
// echo("child send signo[$signo]");
// });
// 处理进程id
if ($pid == -1) {
die('unsupport fork');
} else if ($pid) {
// ???
echo("child-master $pid");// 主进程
} else {
$pid = getmypid(); // 子进程
// 设置用户
posix_setuid(1001);
posix_setgid(1001);
//发送进程退出信号,可以在pcntl_signal接收,可以不配置
// posix_kill($pid,SIGQUIT);
// pcntl_signal_dispatch();
}
}
public function getNum()
{
return pow(10,4);
}
}
$new = new TestController();
$new->start();
pthreads(v3)
注意:仅支持php=7.2(ts版),其它版本有兼容性问题,仅能在命令行下运行,php>7.3 应使用parallel
class BaseThread extends Thread
{
private $i;
public function __construct($i)
{
$this->i = $i;
}
public function run()
{
$data = UserModel::where('testslave','张三')->first();
echo 'this is sub thread id:'.getmypid().' data:'.json_encode($data,true);
}
}
$mythread = new BaseThread(1111);
$mythread->start(PTHREADS_INHERIT_ALL ^ PTHREADS_INHERIT_C);
$mythread->join();//同步阻塞,等待子线程结束
echo 'success';
pht (拷贝未测试)
支持php>=7.2 (ts)
pht 是新一代的pthread
<?php
use pht\Thread;
class Test
{
public static function run(){var_dump(5);}
public static function run2(){var_dump(6);}
}
function aFunc(){var_dump(3);}
$thread = new Thread();
$thread->addFunctionTask(static function($one) {var_dump($one);}, 1);
$thread->addFunctionTask(function() {var_dump(2);});
$thread->addFunctionTask('aFunc');
$thread->addFunctionTask('array_map', function ($n) {var_dump($n);}, [4]);
$thread->addFunctionTask(['Test', 'run']);
$thread->addFunctionTask([new Test, 'run2']);
$thread->start();
$thread->join();
parallel (pthread升级版)
php >=7.2 (ts)
1、parallel\run基本用法
<?php
$task = function($arg){
echo 'child pid:'.getmypid().' input:'.$arg.PHP_EOL;
};
// 开启1个线程
$future = \parallel\run($task,['this is pass '.$i]);
1、parallel\runtime 基本用法
<?php
$task = function($arg){
echo 'child pid:'.getmypid().' input:'.$arg.PHP_EOL;
};
$r = new parallel\Runtime();
$r->run($task,['this is pass string']);
sleep(1);
$r->close(); //同步阻塞,等待子线程结束
echo 'finish';
1、parallel\Channel 基本用法
<?php
$task = function($arg,$ch){
// 往通道内输出,会阻塞等待数据被接收后继续执行
$ch->send([1,3]);
echo 'child pid:'.getmypid().' input:'.$arg.PHP_EOL;
};
$r = new parallel\Runtime();// new一个runtime对象
$ch = new parallel\Channel();// new一个通道对象
$r->run($task,['this is pass string',$ch]);// 创建一个线程
sleep(1);
print_r($ch->recv());// 接收通道数据
$r->close(); //同步阻塞,等待子线程结束 ,$r->kill()会直接杀死子线程
echo 'finish';