| Refresh | Home EGTry.com

create multiple threads, run jobs concurrently.


perl code

use threads;
use Config;
use strict;

#check if threads are supported
if ($Config{usethreads}) {
  print "Thread is supported in this version of perl\n";
} else {
  print "Thread is not supported in this version of perl\n";
  exit; 
}
print "\n";

#create and run threads 
my $thread1=threads->create(\&call, "thread1", 5);
my $thread2=threads->create(\&call, "thread2", 2);

#wait for all thread to finish
$thread1->join();
$thread2->join();

print "\n";
print "all threads run to completion\n";

sub call {
  my ($id, $second)=@_;
  print "START child thread $id\n";
  sleep($second);
  print "DONE in the child thread $id\n";
}



Output

Thread is supported in this version of perl

START child thread thread2
DONE in the child thread thread2
START child thread thread1
DONE in the child thread thread1

all threads run to completion