Madhan
Madhan

Reputation: 1321

How to make multiple threads for a sub routine using perl?

I have an array, which carries the file names that I am going to create. I have written the code below that creates a single file at a time.

use strict;
use File::Slurp;

my @files_to_create=(file_1,file_2......file_100000);
my $File_Con="blah blah...";

foreach my $create_file(@files_to_create){
  &Make_File($create_file);
}

sub create_file{
    my $to_make=shift;
    write_file($to_make,$File_Con);
}

I would like to share the sub routine for multiple scalars in an array.. Hence I can reduce the file creation time.. Can anyone suggest the steps to do...?

Upvotes: 0

Views: 987

Answers (1)

Zaid
Zaid

Reputation: 37146

See perldoc perlthrtut for a very good tutorial on how to use threads in Perl.

use strict;
use warnings;
use threads;

sub create { ... }

my @files_to_create = map { "file_$_" } 1 .. 100_000;
my $config = "blah blah";

my @threads; # To store the threads created

foreach my $file ( @files_to_create ) { # Create a thread for each file

    my $thr = threads->new( \&create, $file, $config );
    push @threads, $thr;
}

$_->join for @threads;  # Waits for all threads to complete

Upvotes: 1

Related Questions