[英]How to run Multiple Functions at the same time in PHP
我正在開發一個PHP腳本,它將優化zip文件中的所有圖像。 我已經編寫了優化單個圖像的功能。 如何使用此功能,以便同時優化所有圖像。 我不知道它是多任務還是多線程。
我目前的操作方式是逐個優化,這會花費太多時間。 有什么辦法可以同時運行多個功能?
<?php
$img1 = "1.jpg";
$img2 = "2.jpg";
$img3 = "3.jpg";
optimize($img1); // \
optimize($img2); // execute these functions in same time
optimize($img3); // /
function optimize($image)
{
// code for optimization
}
?>
您可以使用pcntl_fork()函數,但是會創建新進程。 如果您想編寫多線程程序,PHP不是最佳選擇。
這是PHP 7(pthreads v3 +)的一些示例pthreads代碼:
<?php
class Filter extends Threaded {
public function __construct(string $img, array $filters = [], string $out) {
$this->img = $img;
$this->filters = $filters;
$this->out = $out;
}
public function run() {
$image = imagecreatefromjpeg($this->img);
if (!is_resource($image)) {
throw new \RuntimeException(
sprintf(
"could not create image resource from %s", $this->img));
}
foreach ($this->filters as $filter) {
imagefilter($image, ...$filter);
}
imagejpeg($image,
sprintf("%s/%s",
$this->out, basename($this->img)));
imagedestroy($image);
}
private $img;
private $filters;
private $out;
}
$pool = new Pool(16);
foreach (glob("/path/to/*.JPG") as $image) {
$pool->submit(new Filter(
$image, [
[IMG_FILTER_GRAYSCALE],
[IMG_FILTER_COLORIZE, 100, 50, 0]
],
"/tmp/dump"));
}
$pool->shutdown();
?>
這使用16個線程池來創建所有圖像的棕褐色版本。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.