I'm trying to create and later join a thread in the main part of the perl script, but create the thread in a subroutine, which takes parameters and adds some extra xterm
parameters on to the command passed in. Would it be better to return the thread name (ID?)?
Here is the subroutine
sub run_thread{
my $thread_name = $_[0];
my $cmd = $_[1];
$thread_name = threads->create({'void' => 1},
sub { print("\n$cmd\n"); system($xterm . '-T "' . $cmd . '" -e ' . $cmd) });
}
and in main I'd like to call the sub like so:
my $thr1;
run_thread($thr1, "pwd");
...
$thr1->join();
This doesn't work, and is probably wrong in some way on so many levels. Errors are:
Use of uninitialized value $_[0] in concatenation (.) or string at line 37.
Can't call method "join" on an undefined value at line 21.
I messed around with passing and returning by reference, but not sure on the best way. Please help.
I think you meant
sub run_thread {
my (undef, $cmd) = @_;
$_[0] = threads->create(...);
}
run_thread(my $thread, ...);
$thread->join();
(Assign to the parameter rather than the variable ($thr
) into which the argument (undef) was copied.)
But why would you want to return a value through an argument? Makes far more sense to return it.
sub run_thread {
my ($cmd) = @_;
return threads->create(...);
}
my $thread = run_thread(...);
$thread->join();