Is there any other way ?
Yes. If you spawn a thread early, it will not copy anything created after it is spawned. If you then arrange for it to spawn the threads that you need to spawn later, they will inherit the cleanliness of their parent. Ie. Won't duplicate anything created after that first thread was spawned.
The code below looks complicated, but it is really quite straight forward. If you wrap it into a module and call it before you call your initial module, the api can be pretty transparent.
This just demonstrates the technique; you can do the wrapping to suit your code/style:
#! perl -slw
use strict;
use threads;
use threads::shared;
use Thread::Queue;
my $run :shared = 1;
sub func1 { print "func1: @_"; sleep 1 while $run; }
sub func2 { print "func2: @_"; sleep 1 while $run; }
my $Qspawn = new Thread::Queue;
async {
while( my $parms = $Qspawn->dequeue ) {
my( $type, @args ) = split $;, $parms;
if( $type == 1 ) {
$Qspawn->enqueue( threads->new( \&func1, @args ) );
}
elsif( $type == 2 ) {
$Qspawn->enqueue( threads->new( \&func2, @args ) )
}
else {
warn "Unknown type: $type";
}
}
}->detach;
## now create/allocate your main thread stuff
# require initial;
# initial->import( entrypoints ); ## if needed
# my $init = ...
## When you want to start func1
$Qspawn->enqueue( join $;, 1, 1, 'two', 3.3 );
my $thread1 = $Qspawn->dequeue;
## other stuff
## Now spawn func2
$Qspawn->enqueue( join $;, 2, 2, 'four', 8.8 );
my $thread2 = $Qspawn->dequeue;
## do stuff
## tell func1 & func2 to finish
$run = 0;
## Join them
$_->join for $thread1, $thread2;
## Let the spawner thread clean itself up
exit;
__END__
C:\test>spawner.pl
func1: 1 two 3.3
func2: 2 four 8.8
|