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

In reply to Can't start threads inside a BEGIN{} block by alain_desilets

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.