exec php是多线程吗,如何在PHP应用程序中使用多线程

在php中多线程是可能的。

是的,您可以在PHP中使用螺纹线程是一个面向对象的API,它提供了PHP多线程所需的所有工具。PHP应用程序可以创建、读取、写入、执行和同步线程、工作者和线程对象。

警告在Web服务器环境中不能使用p线程扩展。因此,PHP中的线程应该只保留给基于CLI的应用程序。

简单测试#!/usr/bin/php<?phpclass  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' . "\n", date("g:i:sa"), $this->arg, $sleep);

sleep($sleep);

printf('%s: %s  -finish' . "\n", date("g:i:sa"), $this->arg);

}

}}// Create a array$stack = array();//Initiate Multiple Threadforeach ( range("A", "D") as $i ) {

$stack[] = new AsyncOperation($i);}// Start The Threadsforeach ( $stack as $t ) {

$t->start();}?>

第一轮12:00:06pm:     A  -start -sleeps 512:00:06pm:     B  -start -sleeps 312:00:06pm:     C  -start -sleeps 1012:00:06pm:

D  -start -sleeps 212:00:08pm:     D  -finish12:00:09pm:     B  -finish12:00:11pm:     A  -finish12:00:16pm:

C  -finish

第二轮12:01:36pm:     A  -start -sleeps 612:01:36pm:     B  -start -sleeps 112:01:36pm:     C  -start -sleeps 212:01:36pm:

D  -start -sleeps 112:01:37pm:     B  -finish12:01:37pm:     D  -finish12:01:38pm:     C  -finish12: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\n", $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\n", microtime(true) - $t, strlen($g->data));

} else

printf(" and %f seconds to finish, request failed\n", microtime(true) - $t);}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值