訓練家的快寫筆記

The legend of trainer's paper


搜尋:

     關閉     
標題:完整的 php thread 運作 part2
內容:

<?php
  include '../../../inc/conn.php';
  include '../../../inc/include.php';

  //此版本是多少工作,可以給多少人領,一個完成馬上接下一個工作

  $thread_max_num=3; //-->> $thread_max_num 可以調整
  
  //有多少工作的array

  $works_arr = array();
  for($i=0;$i<10;$i++)  //假設是十個工作
  {
    $works_arr[$i]=array();
  } 
  
  function work_function($t_step,$i)
  {      
    //主要工作就放這裡就好了
    global $thread_max_num; 
    sleep(rand(0,5));  
    echo "works:".($t_step%$thread_max_num)."...".$i." done...\n";
    
  }
  $step=0;
  $t_array=array();
  $t_step=0;
  while($step!=count($works_arr)){
    if(count($t_array)<$thread_max_num)
    {
      $t_array[$t_step] = new Thread('work_function');
      $t_array[$t_step]->start($t_step,$step);
      $step++;
      $t_step++;
    }
    foreach( $t_array as $index => $thread ) {
      if( ! $thread->isAlive() ) {
        unset( $t_array[$index] );
      }
    }
    usleep( 10 ); //-> 可以調整
  };

  while( !empty( $t_array ) ) {
    foreach( $t_array as $index => $thread ) {
      if( ! $thread->isAlive() ) {
        unset( $t_array[$index] );
      }
    }
    usleep( 10 ); //-> 可以調整
  }