Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute a file in parallel / multithreading in PHP

I have a cron file cron/cron1.php. i have set up this for cron running 1 minute.

so for next process it will take 1 minute to execute.

now i want to run this file parallel three times in minute. this file takes execution time more than 2 min.

can i run this file parallel in a single file like this

file1.php

<?php
      include("cron/cron1.php"); // run seperately
      sleep(5);
      include("cron/cron1.php"); // run seperately
       sleep(5);
      include("cron/cron1.php"); // run seperately 

?>

in above file cron1.php will execute 5 seconds difference but when above one is completed its process. as i told you each cron1.php will takes more than 2 minutes to complete. so i couldn't achieve it.

is there any process or multithreading or approch so that i can run each cron1.php every 5 seconds delay. then i will set the file1.php as a cron job.

like image 478
Satish Sharma Avatar asked Nov 30 '22 02:11

Satish Sharma


1 Answers

PHP DOES SUPPORT MULTI-THREADING

http://php.net/pthreads

Here is a multi-threaded example of the kind of logic you require:

<?php
define("SECOND", 1000000);
define("LOG",    Mutex::create());

/*
 * Log safely to stdout
 * @param string message the format string for log
 * @param ... args       the arguments for sprintf
 * @return void
 */
function slog($message, $args = []) {
    $args = func_get_args();
    if ((count($args) > 0) &&
        ($message = array_shift($args))) {
        $time = microtime(true);
        Mutex::lock(LOG);
        echo vsprintf(  
            "{$time}: {$message}\n", $args);
        Mutex::unlock(LOG);
    }
}

class MyTask extends Thread {
    public $id;
    public $done;

    public function __construct($id) {
        $this->id = $id;
        $this->done = false;
    }

    public function run() {
        slog("%s#%d entered ...", __CLASS__, $this->id);
        /* don't use sleep in threads */
        $this->synchronized(function(){
            /* simulate some work */
            $this->wait(10 * SECOND);
        });
        slog("%s#%d leaving ...", __CLASS__, $this->id);
        $this->done = true;
    }
}

$threads = [];

function get_next_id(&$threads) {
    foreach ($threads as $id => $thread) {
        if ($thread->done) {
            return $id;
        }
    }
    return count($threads);
}

do {
    slog("Main spawning ...");
    $id = get_next_id($threads);
    $threads[$id] = new MyTask($id);
    $threads[$id]->start();
    slog("Main sleeping ...");
    usleep(5 * SECOND); 
} while (1);
?>

This will spawn a new thread every 5 seconds, the threads take 10 seconds to execute.

You should try to find ways of increasing the speed of individual tasks, perhaps by sharing some common set of data.

like image 54
Joe Watkins Avatar answered Dec 05 '22 17:12

Joe Watkins