Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use Perl's system call to spawn independent threads?

I would like to call other Perl scripts in order to perform a contention test from with a main Perl script.

Something like this currently works:

system("perl 1.pl");
system("perl 2.pl");
exit;

However, I would like to kick these off as independent threads running at the same time.

I tried, based on my Google searches, doing something like this:

system(1, "perl 1.pl");
system(1, "perl 2.pl");
exit;

That doesn't work. The main script exists immediately, which is fine, but the underlying threads I want to spawn don't get kicked off. I was wondering if there was something else I have to do or if anyone else has done something like this.

Thanks for any help in advance.

like image 464
geoffrobinson Avatar asked Sep 04 '09 17:09

geoffrobinson


2 Answers

use threads;
$thr1 = threads->create('msc', 'perl 1.pl');
$thr2 = threads->create('msc', 'perl 2.pl');

$thr1->join();
$thr2->join();

sub msc{ ## make system call
  system( @_ );
}

This will wait for both to finish executing before the it will exit. I'm guessing this is what you want from your original question, right? If not feel free to drop a comment and edit your post to explain it better, and I'll try again.

like image 113
scragar Avatar answered Sep 28 '22 17:09

scragar


You can fork off processes to run the commands for you. If you do, you will probably want to use exec instead of system:

#!/usr/bin/perl

use strict;
use warnings;

die "could not fork: $!" unless defined (my $first_pid = fork);

#first child
exec $^X, "1.pl" unless $first_pid;

die "could not fork: $!" unless defined (my $second_pid = fork);

#second child
exec $^X, "2.pl" unless $second_pid;

waitpid $first_pid,  0;  #wait for first child to finish
waitpid $second_pid, 0;  #wait for second child to finish

See also: $^X and waitpid

like image 24
Chas. Owens Avatar answered Sep 28 '22 16:09

Chas. Owens