首頁  >  文章  >  php教程  >  非常实用的PHP 多线程,线程池例子

非常实用的PHP 多线程,线程池例子

PHP中文网
PHP中文网原創
2016-05-25 16:59:021020瀏覽


<?php
/*
 * Homepage http://netkiller.github.io
 * Author: netkiller*/
class ExampleWorker extends Worker {

	public function __construct(Logging $logger) {
		$this->logger = $logger;
	}

	protected $logger;	
}

/* the collectable class implements machinery for Pool::collect */
class Work extends Stackable {
	public function __construct($number) {
		$this->number = $number;
	}
	public function run() {
		$this->worker
			->logger
			->log("%s executing in Thread #%lu",
				  __CLASS__, $this->worker->getThreadId());
		sleep(1);
		printf("runtime: %s, %d\n", date(&#39;Y-m-d H:i:s&#39;), $this->number);
		$this->status = "OK";
	}
}

class Logging extends Stackable {

	protected function log($message, $args = []) {
		$args = func_get_args();	

		if (($message = array_shift($args))) {
			echo vsprintf("{$message}\n", $args);
		}
	}
}

$pool = new Pool(5, \ExampleWorker::class, [new Logging()]);

foreach (range(0, 100) as $number) {
	$pool->submit(new Work($number));
}


$pool->shutdown();

var_dump($pool);
?>

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn