PHP Pthreads 實例
PHP Pthreads 是一個多線程擴展,它允許 PHP 程序員使用多線程,進一步提高 PHP 的執行效率和性能。下面簡單介紹幾個 PHP Pthreads 實例。
1. 線程運行結果順序問題
class AsyncOperation extends Thread
{
private $num;
public function __construct($i)
{
$this->num = $i;
}
public function run()
{
echo "Thread " . $this->num . " Start.\n";
sleep(2);
echo "Thread " . $this->num . " End.\n";
}
}
$thread1 = new AsyncOperation(1);
$thread2 = new AsyncOperation(2);
$thread3 = new AsyncOperation(3);
$thread1->start();
$thread2->start();
$thread3->start();
$thread1->join();
$thread2->join();
$thread3->join();
echo "All Threads Finished.\n";
運行結果:Thread1、Thread2、Thread3 順序可能不一致。
解決方法:在 join() 之前添加一個 Thread 的 status 判斷,如下:
do {
$still_running = false;
foreach ([$thread1, $thread2, $thread3] as $thread) {
if ($thread->isRunning()) {
$still_running = true;
break;
}
}
} while ($still_running);
$thread1->join();
$thread2->join();
$thread3->join();
2. 多個線程共享 MySQL 鏈接
class dbThread extends Thread {
private $db;
public function __construct($db) {
$this->db = $db;
}
public function run() {
$conn = new mysqli($this->db['host'], $this->db['user'], $this->db['password'], $this->db['database']);
/* do something */
}
}
$db = array(
'host'=>'127.0.0.1',
'user'=>'root',
'password'=>'root',
'database'=>'test'
);
for ($i=0; $i<10; $i++) {
$thread[$i] = new dbThread($db);
$thread[$i]->start();
}
多線程共享 MySQL 鏈接容易引起問題,如不同的線程使用同一個鏈接庫同時寫入同一個表時會產生死鎖,解決方法是使用連接池,保證連接池內每個連接只有一個線程使用。
3. 線程間數據傳遞
class dataThread extends Thread {
public $data;
public function __construct() {
$this->data = array();
}
public function run() {
/* 傳遞數據 */
$this->data = array('thread_number'=>1, 'name'=>'Peter', 'age'=>25);
}
}
$thread = new dataThread();
$thread->start();
$thread->join();
var_dump($thread->data);
使用類變量傳遞數據時,需要使用 public 或 protected,private 會導致傳遞失敗。
以上就是幾個 PHP Pthreads 實例的介紹,希望能對大家有所幫助。