in reply to How do I run subroutines in parallel?
This example show how to use the share resource of threads. If you want a variable that can be shared by the other threads, just declare it like the example, with : share in the end, don't forget to load the module threads::shared!
Other thing, note that the main is another thread too! If it goes out (exit), the other threads will be closed too. To wait a thread use the command join: $thread->join
#!/usr/bin/perl use threads; use threads::shared; $|=1; my ($global) : shared ; my $thr1 = threads->new(\&TEST,1) ; my $thr2 = threads->new(\&TEST,2) ; my @ReturnData = $thr1->join ; print "Thread 1 returned: @ReturnData\n" ; my @ReturnData = $thr2->join ; print "Thread 2 returned: @ReturnData\n" ; ######## # TEST # ######## sub TEST { my ( $id ) = @_ ; for(0..10) { $global++ ; print "id: $id >> $_ >> GLB: $global\n" ; sleep(1) ; } return( $id ) ; }
|
|---|