问题

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

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

  最佳答案

php中可以使用多线程

是的,您可以在PHP中使用 pthreads 进行多线程

PHP documentation :

Pthreads是一个面向对象的API,它提供了PHP中多线程所需的所有工具. PHP应用程序可以创建、读取、写入、执行和同步Threads,Workers和Threaded对象.

警告: pthreads扩展不能在Web服务器环境中使用.因此,PHP中的线程应该仅限于基于CLI的应用程序.

简单测试

 #!/usr/bin/php
<?php
class AsyncOperation extends Thread {

    public function __construct($arg) {
        $this->arg = $arg;
    }

    public function run() {
        if ($this->arg) {
            $sleep = mt_rand(1, 10);
            printf('%s: %s  -start -sleeps %d' . "
", date("g:i:sa"), $this->arg, $sleep);
            sleep($sleep);
            printf('%s: %s  -finish' . "
", date("g:i:sa"), $this->arg);
        }
    }
}

// Create a array
$stack = array();

//Initiate Multiple Thread
foreach ( range("A", "D") as $i ) {
    $stack[] = new AsyncOperation($i);
}

// Start The Threads
foreach ( $stack as $t ) {
    $t->start();
}

?>
 

第一次运行

 12:00:06pm:     A  -start -sleeps 5
12:00:06pm:     B  -start -sleeps 3
12:00:06pm:     C  -start -sleeps 10
12:00:06pm:     D  -start -sleeps 2
12:00:08pm:     D  -finish
12:00:09pm:     B  -finish
12:00:11pm:     A  -finish
12:00:16pm:     C  -finish
 

第二次运行

 12:01:36pm:     A  -start -sleeps 6
12:01:36pm:     B  -start -sleeps 1
12:01:36pm:     C  -start -sleeps 2
12:01:36pm:     D  -start -sleeps 1
12:01:37pm:     B  -finish
12:01:37pm:     D  -finish
12:01:38pm:     C  -finish
12:01:42pm:     A  -finish
 

真实世界范例

 error_reporting(E_ALL);
class AsyncWebRequest extends Thread {
    public $url;
    public $data;

    public function __construct($url) {
        $this->url = $url;
    }

    public function run() {
        if (($url = $this->url)) {
            /*
             * If a large amount of data is being requested, you might want to
             * fsockopen and read using usleep in between reads
             */
            $this->data = file_get_contents($url);
        } else
            printf("Thread #%lu was not provided a URL
", $this->getThreadId());
    }
}

$t = microtime(true);
$g = new AsyncWebRequest(sprintf("http://www.google.com/?q=%s", rand() * 10));
/* starting synchronization */
if ($g->start()) {
    printf("Request took %f seconds to start ", microtime(true) - $t);
    while ( $g->isRunning() ) {
        echo ".";
        usleep(100);
    }
    if ($g->join()) {
        printf(" and %f seconds to finish receiving %d bytes
", microtime(true) - $t, strlen($g->data));
    } else
        printf(" and %f seconds to finish, request failed
", microtime(true) - $t);
}
 

  相同标签的其他问题

phpmultithreading