简体   繁体   English

如何在PHP中同时运行多个功能

[英]How to run Multiple Functions at the same time in PHP

I am developing a PHP script that will optimize all images in a zip file. 我正在开发一个PHP脚本,它将优化zip文件中的所有图像。 I have written a function to optimize a single image. 我已经编写了优化单个图像的功能。 How can I this function so that all the images will be optimized at the same time. 如何使用此功能,以便同时优化所有图像。 I don't know whether its multitasking or multithreading. 我不知道它是多任务还是多线程。

The current way I'm doing it is optimizing one by one which is taking too much time. 我目前的操作方式是逐个优化,这会花费太多时间。 Is there any way we can run multiple functions at the same time? 有什么办法可以同时运行多个功能?

<?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
}
?>

you can user pcntl_fork() function, but it creates new process. 您可以使用pcntl_fork()函数,但是会创建新进程。 PHP is not best choice, if you want to code multithreading programs. 如果您想编写多线程程序,PHP不是最佳选择。

Here's some example pthreads code, for PHP 7 (pthreads v3+): 这是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();
?>

This uses a Pool of 16 threads to create sepia versions of all the images glob'd. 这使用16个线程池来创建所有图像的棕褐色版本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM