Goroutines in Perl

A <em>goroutine</em> is a lightweight thread of execution.

use strict;
use warnings;
use threads;
use Time::HiRes qw(sleep);

sub f {
    my ($from) = @_;
    for my $i (0..2) {
        print "$from : $i\n";
    }
}

sub main {
    # Calling the function in the usual way, running it synchronously
    f("direct");

    # Invoking the function in a thread
    threads->create(\&f, "threaded")->detach();

    # Starting a thread for an anonymous function call
    threads->create(sub {
        my ($msg) = @_;
        print "$msg\n";
    }, "going")->detach();

    # Waiting for threads to finish
    sleep(1);
    print "done\n";
}

main();

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 thread, use threads->create(\&f, s)->detach(). This new thread will execute concurrently with the calling one.

    threads->create(\&f, "threaded")->detach();

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

    threads->create(sub {
        my ($msg) = @_;
        print "$msg\n";
    }, "going")->detach();

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

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

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

$ perl goroutines.pl
direct : 0
direct : 1
direct : 2
threaded : 0
going
threaded : 1
threaded : 2
done

Next we’ll look at a complement to threads in concurrent Perl programs: channels.