多线程扩展入门
要从多线程开始,你需要用于 php 的 pthreads-ext
,它可以安装
$ pecl install pthreads
并将条目添加到 php.ini
。
一个简单的例子:
<?php
// NOTE: Code uses PHP7 semantics.
class MyThread extends Thread {
/**
* @var string
* Variable to contain the message to be displayed.
*/
private $message;
public function __construct(string $message) {
// Set the message value for this particular instance.
$this->message = $message;
}
// The operations performed in this function is executed in the other thread.
public function run() {
echo $this->message;
}
}
// Instantiate MyThread
$myThread = new MyThread("Hello from an another thread!");
// Start the thread. Also it is always a good practice to join the thread explicitly.
// Thread::start() is used to initiate the thread,
$myThread->start();
// and Thread::join() causes the context to wait for the thread to finish executing
$myThread->join();