Skip to content


multi-threaded Perl, I’ve missed you…

#!/usr/bin/perl -w
use strict ;
my $can_use_threads = eval 'use threads; 1';
die("Your Perl doesn't support threads\n") if (!$can_use_threads) ;

use threads ;
use threads::shared ;

my @threads = () ;

# spin a bunch of threads
for (my $i=0; $i<5; $i++) {
  my $param1 = $i ;
  my $param2 = $i**2 ;
  $threads[$i] = threads->create(\&thread_function, $param1, $param2) or die("couldn't create a thread for i: $i\n") ;
}

# wait for all threads to finish
for (my $i=0; $i<5; $i++) {
  $threads[$i]->join() ;
}

exit ;

sub thread_function
{
  my $param1 = shift ;
  my $param2 = shift ;
  print "Hi there, I'm thread #$param1, my value is $param2\n" ;
}

Posted in howto, webdev.

Tagged with , .


0 Responses

Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.

You must be logged in to post a comment.


Get Adobe Flash playerPlugin by wpburn.com wordpress themes