// 開啟協程化,檔案操作,sleep,Mysqli,PDO,streams等都變成異步IO
Co::set(['hook_flags'=> SWOOLE_HOOK_ALL]);
$s = microtime(true);
// 創建協程容器
Co\run(function() {
// 開啟100個協程執行usleep
for ($c = 100; $c--;) {
go(function () {
for ($n = 100; $n--;) {
usleep(1000);
}
});
}
// 開啟100個協程執行100次檔案讀寫
for ($c = 100; $c--;) {
go(function () use ($c) {
$tmp_filename = "/tmp/test-{$c}.php";
for ($n = 100; $n--;) {
$self = file_get_contents(__FILE__);
file_put_contents($tmp_filename, $self);
assert(file_get_contents($tmp_filename) === $self);
}
unlink($tmp_filename);
});
}
// 開啟50個協程執行100次資料庫查詢
for ($c = 50; $c--;) {
go(function () {
$pdo = new PDO('mysql:host=127.0.0.1;dbname=test;charset=utf8', 'root', 'root');
$statement = $pdo->prepare('SELECT * FROM `user`');
for ($n = 100; $n--;) {
$statement->execute();
assert(count($statement->fetchAll()) > 0);
}
});
}
// 開啟50個協程執行100次資料庫查詢
for ($c = 50; $c--;) {
go(function () {
$mysqli = new Mysqli('127.0.0.1', 'root', 'root', 'test');
$statement = $mysqli->prepare('SELECT `id` FROM `user`');
for ($n = 100; $n--;) {
$statement->bind_result($id);
$statement->execute();
$statement->fetch();
assert($id > 0);
}
});
}
});
echo 'use ' . (microtime(true) - $s) . ' s';
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/6582.html
標籤:PHP
