Laravel Main Thread Blocked

735 views Asked by At

Objective is to convert each page of pdf to image. Therefore I'm using php Imagick and php-vips for this operation. These libraries does the task just fine but the problem is, as soon as the conversion operation begins, main php thread gets blocked. Meaning: no user can access any page, route. Receiving or sending request is also not possible at that moment. So basically server just halts all request and puts them on pending until pdf conversion is done. Here is the code for conversion:

            for ($n = 0; $n < $pageCount; $n++) {
            //Using php vips
            $page = Vips\Image::newFromFile($pathTarget, [
                "dpi" => 200,
                "page" => $n,
                # this enables image streaming
                "access" => "sequential"
            ]);
            $page->writeToFile($pathTarget . "_page_" . $n . ".jpg");
            }

This piece of code is working with php-vips library. The same problem persists with Imagick library too. Even though i tried to limit the Imagick resources so php would have more memory and core left, it didn't resolve anything. Such as:

Imagick::setResourceLimit (6, 1);//for limiting Imagick to 1 CPU core

Question: How can i resolve this blocking issue ? Maybe job queues, async tasks ? cron ? Any idea helps. Thank you.

Important note: This is a local environment, running it using "php artisan serve".

Env specs:

Laravel 5.7

Ubuntu

8GB DDR3 ram

8 core cpu

2

There are 2 answers

0
tamrat On BEST ANSWER

Move the image conversion logic into a job and push it to a queue. Then start up the queue worker and it will handle processing it in the a separate process without blocking the main thread.

3
Mustafa Acar On

When you serve your application with php artisan serve PHP has only one thread and it's busy. that is why you cannot process any other web page requests.

PHP thread works simultaneously. In your case, you have one. but u can have more than one thread on your server.

Like using Nginx and PHP-fpm (and you don't need any configurations for multiple threads it has default configuration for multiple threads.)