user2650277
user2650277

Reputation: 6739

Parallel execution instead of foreach

I currently do file upload sequentially with a foreach loop.Each upload is processed one after the other.

<?php
foreach ($files_array as $file) {
//each image is processed here and upload one after the other
}
?> 

However processing multiple images instead of one at a time would be more efficient as the user will wait a lot less.How can i process multiple files at once in php instead of doing it sequentially with a foreach

Upvotes: 3

Views: 2568

Answers (2)

cn0047
cn0047

Reputation: 17071

Option 1 - fork your process:

You need to fork your process, and fulfill this in few threads. Here my example:

<?php

declare(ticks = 1);

$filesArray = [
    'file-0',
    'file-1',
    'file-2',
    'file-3',
    'file-4',
    'file-5',
    'file-6',
    'file-7',
    'file-8',
    'file-9',
];

$maxThreads = 3;
$child = 0;

pcntl_signal(SIGCHLD, function ($signo) {
    global $child;
    if ($signo === SIGCLD) {
        while (($pid = pcntl_wait($signo, WNOHANG)) > 0) {
            $signal = pcntl_wexitstatus($signo);
            $child--;
        }
    }
});
foreach ($filesArray as $item) {
    while ($child >= $maxThreads) {
        sleep(1);
    }
    $child++;
    $pid = pcntl_fork();
    if ($pid) {
    } else {
        // Here your stuff.
        sleep(2);
        echo posix_getpid()." - $item \n";
        exit(0);
    }
}
while ($child != 0) {
    sleep(3);
}

Option 2 - use work queues:

You can also use queue (for example RabbitMQ or something else).
In your script you can put your job into queue and reply to client that job added to queue and will processed soon. Here you can find detailed example how you can done it with RabbitMQ.

Upvotes: 4

Afzal Khan
Afzal Khan

Reputation: 125

You want to upload multiple images at a time ?

If yes so use the "explode" method to upload multiple images.

Upvotes: -2

Related Questions