Now from what I understand under Perl ithreads all data is private unless explicitly shared.
I want to write a function which stores per thread state between calls. I assume that a side effect of all data being thread private by default would allow me to use a closure like this:
#!/usr/bin/perl -w
use strict;
use threads;
{ # closure to create local static variable
my $per_thread_state = 0;
sub foo {
my $inc = shift;
$per_thread_state += $inc;
return $per_thread_state;
}
}
my $inc = 0;
threads->create(
sub {
my $inc = shift;
my $i = $inc;
while (--$i) {
threads->yield();
print threads->tid().":".foo($inc)."\n";
}
}, $inc
) while (++$inc < $ARGV[0]);
$_->join() foreach threads->list();
When I run it this looks like it works the way I expect, but I just want to be sure because I couldn't find any documentation which explicitly discusses doing something like this.
Could anyone point me to something official looking?
Edit
One other thing that seems strange is that the threads always seem to run in order of creation and don't interleave for some reason. For instance if I run:
./tsd.pl 100
Everything prints out perfectly in order. I'm on Ubuntu 9.04 if it matters.