PHP多進程編程(二)管道通訊

來源:互聯網
上載者:User
一個進程如果是個人英雄主義,那麼多進程就是集體主義。(不嚴格區分多進程 和 多線程的差別)

你不再是一個獨行俠,而是一個指揮家。

獨來獨往,非常自由自在,但是,很多時候,不如眾人拾柴火焰高。

這就是我對多進程的理解。多線程編程的主要問題是:通訊 和 同步問題。

更多PHP 多線程編程的背景知識見:

PHP多進程編程(一)

在PHP 中,如果光用pcntl ,實現比較簡單的通訊問題都是很困難的。

下面介紹管道通訊:

1. 管道可以認為是一個隊列,不同的線程都可以往裡面寫東西,也都可以從裡面讀東西。寫就是

在隊列末尾添加,讀就是在隊頭刪除。

2. 管道一般有大小,預設一般是4K,也就是內容超過4K了,你就只能讀,不能往裡面寫了。

3. 預設情況下,管道寫入以後,就會被阻止,直到讀取他的程式讀取把資料讀完。而讀取進程也會被阻止,

直到有進程向管道寫入資料。當然,你可以改變這樣的預設屬性,用stream_set_block 函數,設定成非阻斷模式。

下面是我分裝的一個管道的類(這個類命名有問題,沒有統一,沒有時間改成統一的了,我一般先寫測試代碼,最後分裝,所以命名上可能不統一):

Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/-->fifoPath = $fifoPath;    }/////////////////////////////////////////////////////  寫管道函數開始///////////////////////////////////////////////////    function open_write()    {        $this->w_pipe = fopen($this->fifoPath, 'w');        if ($this->w_pipe == NULL) {            error("open pipe {$this->fifoPath} for write error.");            return false;        }        return true;    }    function write($data)    {        return fwrite($this->w_pipe, $data);    }    function write_all($data)    {        $w_pipe = fopen($this->fifoPath, 'w');        fwrite($w_pipe, $data);        fclose($w_pipe);    }    function close_write()    {        return fclose($this->w_pipe);    }//////////////////////////////////////////////////////////// 讀管道相關函數開始////////////////////////////////////////////////////////    function open_read()    {        $this->r_pipe = fopen($this->fifoPath, 'r');        if ($this->r_pipe == NULL) {            error("open pipe {$this->fifoPath} for read error.");            return false;        }        return true;    }    function read($byte = 1024)    {        return fread($this->r_pipe, $byte);    }    function read_all()    {        $r_pipe = fopen($this->fifoPath, 'r');        $data = '';        while (!feof($r_pipe)) {            //echo "read one K\n";            $data .= fread($r_pipe, 1024);        }        fclose($r_pipe);        return $data;    }    function close_read()    {        return fclose($this->r_pipe);    }////////////////////////////////////////////////////    /**     * 刪除管道     *     * @return boolean is success     */    function rm_pipe()    {        return unlink($this->fifoPath);    }}?>

有了這個類,就可以實現簡單的管道通訊了,因為這個教程是多進程編程系列教程的一個部分。

這個管道類的應用部分,將放到第三部分。

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.