Hello everyone,

In order to avoid copying too much data, it has previously been suggested (Things you need to know before programming Perl ithreads) that threads can be created inside a BEGIN block, before modules not used by the thread are loaded into memory. When you read the documentation for the threads module, however, it states in the list of bugs that:

"Creating threads inside BEGIN blocks (or during the compilation phase in general) does not work. (In Windows, trying to use fork() inside BEGIN blocks is an equally losing proposition, since it has been implemented in very much the same way as threads.)"

I tried running a simple example (not unlike the one in Things you need to know before programming Perl ithreads), in which I created a thread inside a begin block:

#!perl -w use strict; use threads (); my $test_thread; BEGIN { # start thread before modules are loaded in order to # prevent unnecessary copying of data to thread $|=1; $test_thread = threads->new(sub {for (1..10) { print "$_\n"; sleep + 1;}}); } use Math::BigInt; use IO::Handle; my $bi1 = Math::BigInt->new('1234567890'); my $bi2 = Math::BigInt->new('2345678901'); sleep 3; # give $test_thread some time to start up STDOUT->autoflush(1); print $bi2->bsub($bi1) . "\n"; $test_thread->join();

This produced the following output:

1
2
3
4
1111111011
5
6
7
8
9
10

As far as I can tell, the basic functionality seems to be working and running the script didn't generate any warnings on my system (Win XP using ActiveState Perl). Does anyone know what exactly it is that doesn't work with creating threads inside BEGIN blocks? Are there memory leaks after the thread has been terminated, or what is going on?

Thanks,
sonofason

In reply to Creating threads inside BEGIN blocks by sonofason

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.