swoole协程

编程

php 协程的使用 

异步代码 5秒

<?php

$c = 10;

while($c--) {

echo $c;

go(function () {

//这里使用 sleep 5 来模拟一个很长的命令

echo "aaa

";

co::exec("sleep 5");

});

}

同步代码 50秒

<?php

$c = 10;

while($c--) {

echo $c;

//这里使用 sleep 5 来模拟一个很长的命令

shell_exec("sleep 5");

}

php swooler_co_exec.php 

php swooler_shell_exec.php 

 

协程chan通道

<?php

$chan = new chan(2);

# 协程1

go (function () use ($chan) {

$result = [];

for ($i = 0; $i < 5; $i++)

{

$result += $chan->pop();

}

var_dump($result);

});

# 协程2

go(function () use ($chan) {

$cli = new SwooleCoroutineHttpClient("www.qq.com", 80);

$cli->set(["timeout" => 10]);

$cli->setHeaders([

"Host" => "www.qq.com",

"User-Agent" => "Chrome/49.0.2587.3",

"Accept" => "text/html,application/xhtml+xml,application/xml",

"Accept-Encoding" => "gzip",

]);

$ret = $cli->get("/");

// $cli->body 响应内容过大,这里用 Http 状态码作为测试

sleep(1);

$chan->push(["www.qq.com" => $cli->statusCode]);

});

# 协程3

go(function () use ($chan) {

$cli = new SwooleCoroutineHttpClient("www.163.com", 80);

$cli->set(["timeout" => 10]);

$cli->setHeaders([

"Host" => "www.163.com",

"User-Agent" => "Chrome/49.0.2587.3",

"Accept" => "text/html,application/xhtml+xml,application/xml",

"Accept-Encoding" => "gzip",

]);

$ret = $cli->get("/");

// $cli->body 响应内容过大,这里用 Http 状态码作为测试

$chan->push(["www.163.com" => $cli->statusCode]);

$chan->push(["www.1.com" => 1]);

$chan->push(["www.2.com" => 1]);

$chan->push(["www.3.com" => 1]);

$chan->push(["www.4.com" => 1]);

});

SwooleRuntime::enableCoroutine();

go(function () {

echo "a";

defer(function () {

echo "~a";

});

echo "b";

defer(function () {

echo "~b";

});

sleep(1);

echo "c";

});

 

以上是 swoole协程 的全部内容, 来源链接: utcz.com/z/512483.html

回到顶部