Skip to content

PHP Multithreading Example

logger = $logger;
    }
    
    protected $logger;    
}

/* the collectable class implements machinery for Pool::collect */
class WebWork extends Collectable {
    public function run() {
        $this->worker
            ->logger
            ->log("%s executing in Thread #%lu",
                  __CLASS__, $this->worker->getThreadId());
                  $con = mysql_connect('localhost','
root','');
             $res = mysql_select_db('tests',$con);
             
              mysql_query("SELECT COUNT(*) FROM `tests`.`t`",$con);
            mysql_query("INSERT INTO `tests`.`t` (`id`, `s`, `t`, `date`) VALUES (NULL, '1', '1', CURRENT_TIMESTAMP);",$con)    ; 
        $this->setGarbage();
    }
}

class SafeLog extends Stackable {
    
    protected function log($message, $args = []) {
        $args = func_get_args();    
        
        if (($message = array_shift($args))) {
            echo vsprintf(
                "{$message}\n", $args);
        }
        
        
    }
}

$pool = new Pool(10, 'WebWorker', [new SafeLog()]);

foreach(range(1,100000) as $k) {
$pool->submit($w=new WebWork());
$pool->submit(new WebWork());
$pool->submit(new WebWork());
}

$pool->shutdown();

$pool->collect(function($work){
    return $work->isGarbage();
});

var_dump($pool);
?>
0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments