Calling a function in a background thread / process (forking) Calling a function in a background thread / process (forking) php php

Calling a function in a background thread / process (forking)


From "Tudor Barbu's professional blog"
(http://blog.motane.lu/2009/01/02/multithreading-in-php/)

require_once( 'Thread.php' );// test to see if threading is availableif( ! Thread::isAvailable() ) {    die( 'Threads not supported' );}// function to be ran on separate threadsfunction paralel( $_limit, $_name ) {    for ( $index = 0; $index < $_limit; $index++ ) {        echo 'Now running thread ' . $_name . PHP_EOL;        sleep( 1 );    }}// create 2 thread objects$t1 = new Thread( 'paralel' );$t2 = new Thread( 'paralel' );// start them$t1->start( 10, 't1' );$t2->start( 10, 't2' );// keep the program running until the threads finishwhile( $t1->isAlive() && $t2->isAlive() ) {}

Download Thread.php


If you are using Linux you can take advantage of the command line and do

public function newWrapperInstance($start,$end){    exec('bash -c "exec nohup setsid php-cli yourFile.php '.$start.' '.$end.' > /dev/null 2>&1 &"');}

This will create a new instance of PHP in the background and detach itself from the exec function in the primary thread.

Warning:The only downside is you can't control what those threads do once they are created.