標籤:
今天研究了worker stackable的配合方法,寫了兩種形式,雖然能工作,但是都會出現記憶體不聽增長的問題;
於是把第一個方法的代碼郵件給了作者,到現在他沒有回複我。
我最後放棄兩者配合的方式,直接使用worker,發現到現在執行了582000個工作,記憶體沒有增長,速度也基本穩定,代碼如下:
[php] view plain copy print ?
- <?php
- ini_set(‘zend.enable_gc‘, true);
-
- class ExampleWorker extends Worker {
- public $stack_count = 0;
- public function __construct() {}
- public function run(){
- sleep(1);//waiting for data
- $count = 0;
- $data_flag = true;
- $stime = microtime(true);
- while(1){
- if($data = $this->shift()){
- $data_flag = true;
- $this->doSomeWork();
- if((++$count)%1000==0){
- printf("Work Mermory used %.3fMB RAM, time: %3f===> %d \n",
- memory_get_peak_usage(true)/1048576, (microtime(true) - $stime), $count);
- $stime = microtime(true);
- }
- }else{
- usleep(100000);
- }
- }
- exit;
- }
- private function doSomeWork(){
- $str = ‘sdalsadkfkasd;lfksa;ldfkas;lkf;lsadkf;as‘;
- $len = strlen($str);
-
- $s = substr($str,rand(0,$len));
- $len = floor(strlen($s)/2);
-
- for($i=0;$i<$len;$i++){
- $tmp = $s[$i];
- $idx = intval($len-$i-1);
-
- $s[$i] = $s[$idx];
- $s[$idx] = $tmp;
- }
- }
- }
-
- $worker= new ExampleWorker(sprintf("Worker [%d]", 0));
- $worker->start();
-
- $stime = microtime(true);
- $count = 3000000;//99999999;
- $total = $count*5;
-
- $ct = 0;
- while($count--){
- //for ($target = 0; $target < 5; $target++)
- $worker[]=‘data_‘.(++$ct);
- usleep(rand(200,1800));
- }
- //sleep(10);
- $runtime = (microtime(true)-$stime);
- printf("---------------------------------------------------------\n");
- printf("Used time is %f \n", $runtime);
- printf("Mermory used %.3fMB RAM, added %d, left %d\n", memory_get_peak_usage(true)/1048576, $total, count($worker));
- printf("---------------------------------------------------------\n");
-
- //var_dump($works);
虛擬上的運行速度:
[plain] view plain copy print ?
- Work Mermory used 0.250MB RAM, time: 2.141709===> 607000
- Work Mermory used 0.250MB RAM, time: 1.721918===> 608000
- Work Mermory used 0.250MB RAM, time: 1.858363===> 609000
- Work Mermory used 0.250MB RAM, time: 1.734542===> 610000
- Work Mermory used 0.250MB RAM, time: 1.819794===> 611000
- Work Mermory used 0.250MB RAM, time: 1.847132===> 612000
- Work Mermory used 0.250MB RAM, time: 1.740353===> 613000
- Work Mermory used 0.250MB RAM, time: 1.628364===> 614000
- Work Mermory used 0.250MB RAM, time: 1.731518===> 615000
- Work Mermory used 0.250MB RAM, time: 1.730583===> 616000
- Work Mermory used 0.250MB RAM, time: 1.825315===> 617000
- Work Mermory used 0.250MB RAM, time: 1.762334===> 618000
- Work Mermory used 0.250MB RAM, time: 1.842860===> 619000
- Work Mermory used 0.250MB RAM, time: 1.732677===> 620000
php pthreads 多線程擴充的使用:一個較為穩定例子。