我敢肯定,我正在嘗試的是非常簡單的,但我從來沒有用過多線程之前,所以我不知道從哪裏開始。在PHP中的子進程之間共享變量?
我使用PCNTL來創建一個多線程的PHP應用程序。我想要做的是有3個函數同時運行,我希望他們的返回值合併成一個單一的數組。因此在邏輯上,我需要一個變量共享他們追加結果的所有孩子之間共享的變量,或者三個變量只在一個孩子和父母之間共享 - 然後父母可以在稍後合併結果。
問題是 - 我不知道如何做到這一點。首先想到的是使用shared memory,但我覺得應該有一個更簡單的方法。
此外,如果它有任何作用,分叉進程的函數是公共類方法。所以,我的代碼看起來像下面這樣:
<?php
class multithreaded_search {
/* ... */
/* Constructors and such */
/* ... */
public function search($string = '') {
$search_types = array('tag', 'substring', 'levenshtein');
$pids = array();
foreach($search_types as $type) {
$pid = pcntl_fork();
$pids[$pid] = $type;
if($pid == 0) { // child process
/* confusion */
$results = call_user_func('multithreaded_search::'.$type.'_search', $string);
/* What do we do with $results ? */
}
}
for($i = 0; $i < count($pids); $i++) {
$pid = pcntl_wait();
/* $pids[$pid] tells me the type of search that just finished */
/* If we need to merge results in the parent, we can do it here */
}
/* Now all children have exited, so the search is complete */
return $results;
}
private function tag_search($string) {
/* perform one type of search */
return $results;
}
private function substring_search($string) {
/* perform one type of search */
return $results;
}
private function levenshtein_search($string) {
/* perform one type of search */
return $results;
}
}
?>
這樣,我需要使用shmop_open
我打電話pcntl_fork
前創建共享內存並保存結果出現,還是孩子們分享類變量?還是他們只共享全局變量?我相信答案很簡單......我只是不知道。
這很有道理,但我該如何讓孩子在父母的範圍內編輯一個變量呢?我必須使用共享內存,還是有其他方法? – stevendesu 2012-01-03 02:59:58
你不能。 PHP不提供必要的低級內存訪問,讓您找出父內存的位置並直接與它通信。即使您可以通過指針或其他方法訪問父進程的內存,也不能保證父進程的內存佈局與孩子的內存佈局保持一致。你必須處理php引擎的內部存儲器映射以找出變量的位置等等......使用共享內存,或者在兩個進程之間打開一個雙向通信通道,並構建一個小數組api來發回數據並且。 – 2012-01-03 12:41:00
我已經使用共享內存現在寫了一個答案,但我喜歡雙向通信通道的想法(特別是因爲這不會限制返回值,而您必須以字節爲單位定義共享內存的大小) 。我該如何着手創建? – stevendesu 2012-01-03 15:44:24