alain_desilets has asked for the wisdom of the Perl Monks concerning the following question:
I'm starting this in a new node, even though it seems closely related to one I wrote last week: Why do my threads sometimes die silenty?.
I am trying to start a pool of threads inside a BEGIN{} block, as per the recommendation on Things you need to know before programming Perl ithreads. My reasons for doing this is that my program loads some modules which are not thread safe, so I want to make sure that the threads in the pool are started before those modules are actually instantiated.
Below is a piece of code which tries to do that.
my $num_threads = 2; my $thr = []; BEGIN { use threads; my $fct = sub { print "hello\n"; open FILE, ">>./hello.dat"; print FILE "hello\n"; close FILE }; for (my $ii=0; $ii<$num_threads; $ii++) { $thr->[$ii] = threads->create($fct); print "\$ii=$ii, started $thr->[$ii]$thr->[$ii]=$thr->[$ii]\n" +; $thr->[$ii]->join(); } } print "done\n";
However, when I run it as is, all I get is the final "done", and the file "hello.dat" doesn't even get created. However, if I comment out the line:
BEGIN {
and its corresponding closing brace, I get the expected output
$ii=0, started threads=SCALAR(0x14d271c)threads=SCALAR(0x14d271c)=thre +ads=SCALAR(0x14d271c) hello $ii=1, started threads=SCALAR(0x14d273c)threads=SCALAR(0x14d273c)=thre +ads=SCALAR(0x14d273c) hello done
and the "hello.dat" file does get created and contains the two "hello" messages.
Can somebody explain to me why the threads don't actually run when they are inside a BEGIN {} block, but do when they aren't?
Thx
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Can't start threads inside a BEGIN{} block
by clueless newbie (Curate) on Sep 26, 2011 at 20:17 UTC | |
|
Re: Can't start threads inside a BEGIN{} block
by ikegami (Patriarch) on Sep 26, 2011 at 20:15 UTC | |
by ikegami (Patriarch) on Sep 26, 2011 at 20:21 UTC | |
by alain_desilets (Beadle) on Sep 26, 2011 at 20:57 UTC |