是否有一种可行的方法在PHP中实现多线程模型,无论是真正的,还是只是模拟它。以前曾有人建议,可以强制操作系统加载PHP可执行文件的另一个实例,并同时处理其他进程。

这样做的问题是,当PHP代码完成执行时,PHP实例仍然保留在内存中,因为没有办法从PHP内部杀死它。所以如果你正在模拟几个线程,你可以想象会发生什么。所以我仍然在寻找一种方法,多线程可以在PHP中有效地完成或模拟。什么好主意吗?


当前回答

那么pcntl_fork呢?

检查我们的手册页的例子:PHP pcntl_fork

<?php

    $pid = pcntl_fork();
    if ($pid == -1) {
        die('could not fork');
    } else if ($pid) {
        // we are the parent
        pcntl_wait($status); //Protect against Zombie children
    } else {
        // we are the child
    }

?>

其他回答

我知道这是一个老问题,但对于搜索的人来说,有一个用C编写的PECL扩展,现在提供了PHP多线程功能,它位于https://github.com/krakjoe/pthreads

如果您正在使用Linux服务器,则可以使用

exec("nohup $php_path path/script.php > /dev/null 2>/dev/null &")

如果你需要传递一些参数

exec("nohup $php_path path/script.php $args > /dev/null 2>/dev/null &")

在script.php

$args = $argv[1];

或者使用Symfony https://symfony.com/doc/current/components/process.html

$process = Process::fromShellCommandline("php ".base_path('script.php'));
$process->setTimeout(0);     
$process->disableOutput();     
$process->start();

那么pcntl_fork呢?

检查我们的手册页的例子:PHP pcntl_fork

<?php

    $pid = pcntl_fork();
    if ($pid == -1) {
        die('could not fork');
    } else if ($pid) {
        // we are the parent
        pcntl_wait($status); //Protect against Zombie children
    } else {
        // we are the child
    }

?>

我知道这是一个老问题,但毫无疑问,PHPThreads对许多人都很有用

代码示例:

function threadproc($thread, $param) {
 
    echo "\tI'm a PHPThread.  In this example, I was given only one parameter: \"". print_r($param, true) ."\" to work with, but I can accept as many as you'd like!\n";
 
    for ($i = 0; $i < 10; $i++) {
        usleep(1000000);
        echo "\tPHPThread working, very busy...\n";
    }
 
    return "I'm a return value!";
}
 

$thread_id = phpthread_create($thread, array(), "threadproc", null, array("123456"));
 
echo "I'm the main thread doing very important work!\n";
 
for ($n = 0; $n < 5; $n++) {
    usleep(1000000);
    echo "Main thread...working!\n";
}
 
echo "\nMain thread done working.  Waiting on our PHPThread...\n";
 
phpthread_join($thread_id, $retval);
 
echo "\n\nOur PHPThread returned: " . print_r($retval, true) . "!\n";

需要PHP扩展:

posix pcntl 套接字

我已经在生产中使用这个库好几个月了。我花了很多精力让它看起来像在使用POSIX pthread。如果您熟悉pthread,那么您可以立即学习并非常有效地使用它。

在计算上,内部工作方式有很大不同,但实际上,功能几乎是相同的,包括语义和语法。

我用它编写了一个非常高效的WebSocket服务器,支持高吞吐率。对不起,我跑题了。我只是很兴奋,我终于把它发布了,我想看看它会帮助谁!

您可以模拟线程。PHP可以通过popen(或proc_open)运行后台进程。这些进程可以通过stdin和stdout进行通信。当然,这些进程本身也可以是一个php程序。这可能是你能找到的最接近的了。