2024 年 PHP 日本研討會

Thread 類別

(PECL pthreads >= 2.0.0)

簡介

當 Thread 的 start 方法被呼叫時,run 方法的程式碼將會在一個獨立的執行緒中平行執行。

run 方法執行完畢後,執行緒會立即退出,並在適當的時間與建立它的執行緒合併。

警告

依賴引擎來決定執行緒何時應該合併可能會導致非預期的行為;程式設計師應該盡可能明確地指定。

類別概要

類別 Thread 繼承自 Threaded 實作 Countable, Traversable, ArrayAccess {
/* 方法 */
公開 getCreatorId(): 整數
公開 靜態 getCurrentThread(): Thread
公開 靜態 getCurrentThreadId(): 整數
公開 join(): 布林值
公開 start(整數 $options = ?): 布林值
/* 繼承的方法 */
公開 Threaded::chunk(整數 $size, 布林值 $preserve): 陣列
公開 Threaded::merge(混合 $from, 布林值 $overwrite = ?): 布林值
公開 Threaded::run():
公開 Threaded::synchronized(閉包 $block, 混合 ...$args): 混合
公開 Threaded::wait(整數 $timeout = ?): 布林值
}

目錄

新增註解

使用者貢獻的註解 2 則註解

german dot bernhardt at gmail dot com
8 年前
<?php
# 錯誤:全域變數導入

$tester=true;

function
tester(){
global
$tester;
var_dump($tester);
}

tester(); // 顯示 -> bool(true)

class test extends Thread{
public function
run(){
global
$tester;
tester(); // 顯示 -> NULL
}
}
$workers=new test();
$workers->start();

?>
german dot bernhardt at gmail dot com
10 年前
<?php

class workerThread extends Thread {
public function
__construct($i){
$this->i=$i;
}

public function
run(){
while(
true){
echo
$this->i;
sleep(1);
}
}
}

for(
$i=0;$i<50;$i++){
$workers[$i]=new workerThread($i);
$workers[$i]->start();
}

?>
To Top