Goroutines in PHP

A goroutine is a lightweight thread of execution.

<?php
function f($from) {
    for ($i = 0; $i < 3; $i++) {
        echo "$from : $i\n";
    }
}

f("direct");

// To invoke this function in a goroutine, you can use the `pcntl_fork` function in PHP.
// This new goroutine will execute concurrently with the calling one.
$pid = pcntl_fork();
if ($pid == -1) {
    die("could not fork");
} elseif ($pid) {
    // parent process
} else {
    f("goroutine");
    exit(); // child process must call exit
}

// You can also start a goroutine for an anonymous function call.
$pid = pcntl_fork();
if ($pid == -1) {
    die("could not fork");
} elseif ($pid) {
    // parent process
} else {
    echo "going\n";
    exit(); // child process must call exit
}

// Our two function calls are running asynchronously in
// separate goroutines now. Wait for them to finish.
sleep(1);
echo "done\n";
?>

Suppose we have a function call f($s). Here’s how we’d call that in the usual way, running it synchronously.

f("direct");

To invoke this function in a goroutine, you use pcntl_fork. This new goroutine will execute concurrently with the calling one.

$pid = pcntl_fork();
if ($pid == -1) {
    die("could not fork");
} elseif ($pid) {
    // parent process
} else {
    f("goroutine");
    exit(); // child process must call exit
}

You can also start a goroutine for an anonymous function call.

$pid = pcntl_fork();
if ($pid == -1) {
    die("could not fork");
} elseif ($pid) {
    // parent process
} else {
    echo "going\n";
    exit(); // child process must call exit
}

Our two function calls are running asynchronously in separate goroutines now. Wait for them to finish.

sleep(1);
echo "done\n";

When we run this program, we see the output of the blocking call first, then the output of the two goroutines. The goroutines’ output may be interleaved, because goroutines are being run concurrently by the PHP runtime.

$ php goroutines.php
direct : 0
direct : 1
direct : 2
goroutine : 0
going
goroutine : 1
goroutine : 2
done

Next we’ll look at a complement to goroutines in concurrent PHP programs: process control functions.