PHP pthreads join方法主要用于等待多線程結束,以確保多個線程執行完畢之后才繼續主線程的執行。下面簡單介紹使用
例1:
class MyThread extends Thread {
public function run() {
echo 'Hello World!' . PHP_EOL;
}
}
$thread = new MyThread();
$thread->start();
$thread->join(); // 讓主線程等待該子線程執行完畢
echo 'Main Thread' . PHP_EOL;
運行以上代碼,會輸出“Hello World!”和“Main Thread”,這說明子線程和主線程是有順序關系的。
例2:
class MyThread extends Thread {
public function run() {
for ($i = 0; $i < 3; $i++) {
echo 'MyThread:' . $i . PHP_EOL;
usleep(1000);
}
}
}
$threads = [];
for ($i = 0; $i < 3; $i++) {
$threads[$i] = new MyThread();
}
foreach ($threads as $thread) {
$thread->start();
}
foreach ($threads as $thread) {
$thread->join();
}
echo 'Main Thread' . PHP_EOL;
運行以上代碼,會輸出每個子線程的循環次數和“Main Thread”。
例3:
class MyThread extends Thread {
public function run() {
sleep(5);
}
}
$threads = [];
for ($i = 0; $i < 3; $i++) {
$threads[$i] = new MyThread();
}
foreach ($threads as $thread) {
$thread->start();
}
foreach ($threads as $thread) {
$thread->join();
}
echo 'Main Thread' . PHP_EOL;
運行以上代碼,會休眠5秒,然后輸出“Main Thread”。
總結:在使用PHP中的多線程擴展時,盡量使用join方法確保多個線程執行完畢之后再繼續主線程的執行。