concurrency in PHP concurrency in PHP php php

concurrency in PHP


There is no threading support in PHP. You can however use the pcntl extension to spawn and manage forks, but it would be best to have a second look at your algorithms if you reached the conclusion that things should be done with threading.

An option for processing long running operations asynchronously would be to store them in a database, and have a background worker process take them from the database, calculate the results, then store the results in the database. Then the front facing script would look them up in the database to see if they're completed and what the result is.


Check out the pcntl extension. PHP doesn't support true threading at all, so you'll have to implement pseudo-threads by fork()ing. Note that fork()ing a process is much "heavier" than spawning a thread.


PHP hasn't implemented threads (and likely never will) because many of PHP's libraries are NOT thread safe. That alterative is pcntl which wraps the C fork function.

I've created a handy wrapper for these functions that let me manage them at a higher level.

$thread1 = new Thread( function( $thread ) {    sleep( 4 );    $thread->write( "Hello\n" );} );$thread2 = new Thread( function( $thread ) {    sleep( 5 );    $thread->write( "World\n" );} );$thread3 = new Thread( function( $thread ) {    sleep( 6 );} );print $thread1->read(); // time: 0 -> 4print $thread2->read(); // time: 4 -> 5$thread3->join(); // time 5 -> 6// More advanced handling:// Thread::selectUntilJoin( array( $thread1, $thread2, $thread3 ), function () { ... }, function () { ... } );