PHP 多進程實踐(3)

來源:互聯網
上載者:User
PHP 多進程實踐(三)

5. windows多線程

windows系統不支援pcntl函數,幸好有curl_multi_exec()這個工具,利用內部的多線程,訪問多個連結,每個連結可以作為一個任務。


編寫指令碼 test1.php

 $task){     $ch[$i] = curl_init();     curl_setopt($ch[$i], CURLOPT_URL, $task);     curl_setopt($ch[$i], CURLOPT_RETURNTRANSFER, 1);     curl_multi_add_handle($mh, $ch[$i]);}do {$mrc = curl_multi_exec($mh,$active); } while ($mrc == CURLM_CALL_MULTI_PERFORM);while ($active && $mrc == CURLM_OK) {     if (curl_multi_select($mh) != -1) {       do {$mrc = curl_multi_exec($mh, $active); } while ($mrc == CURLM_CALL_MULTI_PERFORM);     }}// completed, checkout resultforeach ($tasks as $j => $task){     if (curl_error($ch[$j])){          echo "task ${j} [$task ] error " , curl_error($ch[$j]), "\r\n" ;     } else {          echo "task ${j} [$task ] get: \r\n" , curl_multi_getcontent($ch[$j]), "\r\n" ;     }}?>



編寫指令碼 test2.php





用命令列運行

#php -f test1.php &


輸出結果

task 0 [http://localhost/feedbowl/t2.php?job=task1] get:
child start, pid 5804
5804 2013-01-15 20:22:35
5804 2013-01-15 20:22:36
5804 2013-01-15 20:22:37
5804 2013-01-15 20:22:38
5804 2013-01-15 20:22:39

task 1 [http://localhost/feedbowl/t2.php?job=task2] get:
child start, pid 5804
5804 2013-01-15 20:22:35
5804 2013-01-15 20:22:36
5804 2013-01-15 20:22:37
5804 2013-01-15 20:22:38
5804 2013-01-15 20:22:39

task 2 [http://localhost/feedbowl/t2.php?job=task3] get:
child start, pid 5804
5804 2013-01-15 20:22:35
5804 2013-01-15 20:22:36
5804 2013-01-15 20:22:37
5804 2013-01-15 20:22:38
5804 2013-01-15 20:22:39

從列印的時間看到,多個任務幾乎是同時啟動並執行。


  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.