Here is another way to slow things down for visualization. Add a delay in the thread sub.
sub thread {
my $val = shift;
foreach my $x (1..10) {
print "hello $x from thread $val\n";
my $delay = int rand 5;
sleep $delay;
}
}
it seems that perl's idea of multithreading is just as good as calling the avarage subroutine :/ On a single cpu machine, that is true. In real world work, threading is more useful as a means of easily sharing variables between different code blocks running independently, using threads::shared. Otherwise, forking is usually a better parallel processing solution because of issues like memory reclamation, independence of IO, sharing objects, and a few others gotchas which threads occaisionally cause. For example, look how easy it is for the main thread and the child thread can share the array:
#!/usr/bin/perl
use warnings;
use threads;
use threads::shared;
use strict;
$|=1; #turn off buffering
my @hosts_shared : shared; #declare as shared before setting value
@hosts_shared = (1,2,3,4,5);
print "@hosts_shared\n";
my $thread = threads->new(sub {
print "Run the thread! array should be modified\n";
#modify shared array
push @hosts_shared, 42;
})->detach();
sleep 1; # cheap hack to allow thread time to work
print "@hosts_shared\n";
print "Hit enter to exit\n";
<>;
|