moh*_*sen 5 php multithreading class yii2
如何创建自定义类而不是扩展组件类?
课程:
namespace common\components;
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' . "<br />", date("g:i:sa"), $this->arg, $sleep);
sleep($sleep);
printf('%s: %s -finish' . "<br />", date("g:i:sa"), $this->arg);
}
}
}
Run Code Online (Sandbox Code Playgroud)
yii2控制器:
public function actionTest() {
// Create a array
$stack = array();
//Iniciate Miltiple Thread
foreach (range("A", "D") as $i) {
$stack[] = new AsyncOperation($i);
}
// Start The Threads
foreach ($stack as $t) {
$t->start();
}
}
Run Code Online (Sandbox Code Playgroud)
错误:
PHP Fatal Error – yii\base\ErrorException
Class 'common\components\Thread' not found
Run Code Online (Sandbox Code Playgroud)
这个类在纯PHP应用程序中运行完美
而且安装了Pthread!