PHP Conference Japan 2024

pthreads

新增註解

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

anonymous at example dot com
7 年前
以下是我收集的一些關於 PHP pThreads v3 的注意事項
- 命名空間:它不理解命名空間。
- 全域變數:它根本不會序列化 GLOBALS!也不會註冊新的全域變數。
- 類別:它可以正常註冊新的類別。
- 函式:不會註冊任何函式 - 它們都必須放在靜態類別中。它可以理解 PHP 內建函式。
- 常數:先前的常數會轉移過來。但不要建立任何新的常數!
- pThreads 只能在 CLI 中運作 - 當然!
- 如果執行緒崩潰,它會自動重新建立。
- 為了「強制終止」任何執行緒,必須終止父執行緒。或者等到所有其他排隊的任務完成,然後再終止。
- 在 pThread 中註冊的任何東西似乎都不會加入主執行緒…這很好!
-pThreads 在多核心環境中非常強大,但需要注意系統資源…如果配置錯誤,它可能會鎖定系統。
-最後,要找到 PHP pThreads 的幫助資訊少之又少…尤其是 v3 版本!

祝好運!
meadowsjared at gmail dot com
3 年前
在此範例中,展示了如何使用帶有池的執行緒來獲取結果陣列,使用 pThreads v3.2.1 和 php 7.3.23

<?php
class TestWork extends Threaded {
//updated version that works with pThreads v3.2.1 and php 7.3.23
protected $complete;
//$pData is the data sent to your worker thread to do it's job.
public function __construct($pData) {
//transfer all the variables to local variables
$this->complete = false;
$this->testData = $pData;
}
//This is where all of your work will be done.
public function run() {
usleep(2000000); //sleep 2 seconds to simulate a large job
$this->complete = true;
}
public function
isDone() {
return
$this->complete;
}
}
class
ExamplePool extends Pool {
public
$data = array(); // used to return data after we're done
private $numTasks = 0; // counter used to know when we're done
/**
* override the submit function from the parent
* to keep track of our jobs
*/
public function submit(Threaded $task) {
$this->numTasks++;
parent::submit($task);
}
/**
* used to wait until all workers are done
*/
public function process() {
// Run this loop as long as we have
// jobs in the pool
while (count($this->data) < $this->numTasks) {
$this->collect(function (TestWork $task) {
// If a task was marked as done
// collect its results
if ($task->isDone()) {
$tmpObj = new stdclass();
$tmpObj->complete = $task->complete;
//this is how you get your completed data back out [accessed by $pool->process()]
$this->data[] = $tmpObj;
}
return
$task->isDone();
});
}
// All jobs are done
// we can shutdown the pool
$this->shutdown();
return
$this->data;
}
}
$pool = new ExamplePool(3);
$testData = 'asdf';
for(
$i=0;$i<5;$i++) {
$pool->submit(new TestWork($testData));
}
$retArr = $pool->process(); //get all of the results
echo '<pre>';
print_r($retArr); //return the array of results (and maybe errors)
echo '</pre>';
?>
jasonrlester at yahoo dot com
10 年前
請注意,此擴充套件*是* POSIX 執行緒的高階實現,包括在 Windows 上(這就是需要 pthreadsV*.dll 的原因)
admin at deosnet dot com
10 年前
您好,

警告:在執行緒的可呼叫函式中使用可堆疊物件時,如果將其用作陣列,則必須非常小心。實際上,如果您不將可堆疊「陣列」複製到局部變數中,執行時間可能會大幅下降!

此外,如果您想在函式中修改 array(),您也需要將其儲存在局部變數中,以便您的陣列處於執行緒安全環境中。
To Top