Perl Advent Calendar 2007-12-11


by Jerrad Pierce

My apologies for the gaps in the calendar. The elves have been occupied, and I've been up for 48 hours working on term papers but have decided to take a quick break.

forks is an XS-based module which serves as a drop-in replacement for threads. This can be handy in the event that your platform or build of perl doesn't support threads. To make use of the module simply:

nick@nog% perl -pi~ -e 's/\bthreads\b/forks/ .. 0' script

And that's all there is to it! Alternatively, the installer gives you the option of installing stubs in place of (the non-existent) threads and threads:shared so that you can use forks transparently.

In my cursory review of the module—15% of the tests failed, and the sample code ran regardless—I noticed one small difference between ithreads and forks. Whereas ithreads emits the following when executing the sample code:

A thread exited while 4 other threads were still running.
forks offers a bit more detail…
Perl exited with active threads:
        1 running and unjoined
        2 finished and unjoined
        0 running and detached

   1 #lifted from perlthrtut
   2 use forks;
   4 sub loop {
   5         my $thread = shift;
   6         my $foo = 50;
   7         while($foo--) { print "in thread $thread\n" }
   8         threads->yield;
   9         $foo = 50;
  10         while($foo--) { print "in thread $thread\n" }
  11 }
  13 my $thread1 = threads->new(\&loop, 'first');
  14 my $thread2 = threads->new(\&loop, 'second');
  15 my $thread3 = threads->new(\&loop, 'third');