develooper Front page | perl.perl5.porters | Postings from July 2002

Re: Thread::Use - use a module inside a thread only

From:
Elizabeth Mattijsen
Date:
July 30, 2002 00:57
Subject:
Re: Thread::Use - use a module inside a thread only
Message ID:
4.2.0.58.20020730094257.02e62100@mickey.dijkmat.nl
At 09:36 AM 7/30/02 +0200, Rafael Garcia-Suarez wrote:
>Elizabeth Mattijsen wrote:
>>Thread::Use - use a module inside a thread only
>>=head1 SYNOPSIS
>>     use Thread::Use;
>>     threads->new( sub {
>>      useit Module;
>>      useit Module qw(parameters);
>>      noit Module;
>>      noit Module qw(parameters);
>>     } );
>OK, I looked a bit at this, and I must confess that I don't
>understand how/why it works.

I've finally done it...   ;-)

The how is actually by declaring a UNIVERSAL::useit and UNIVERSAL::noit 
routine.


>Looks like stashes are not shared between threads. How
>is this related to saving memory ?

Indeed, stashes are not shared between threads.  Which is also why 
Thread::Needs works: it removes unneeded stashes from the memory in a thread.
However, Thread::Use can also be handy for modules that do not survive the 
cloning process, such as PerlIO::gzip and many DBI::DBD modules...


>... (for modules that don't
>export lots of symbols into the caller's namespace).

If you do some memory benchmarks, you'd be surprised to see how much memory 
is used by exported symbols.  And all of it copied to any thread that is 
created.  Using significant amounts of CPU and memory.  Which becomes 
important in many, long running thread situations as mod_perl with the 
worker MPM of Apache.


>Does the module gets unloaded in some way when the thread
>ends ?

When a thread starts, a clone of the _entire_ interpreter is made, 
including any modules that are loaded.  However, any modules that you load 
when in the cloned interpreter (thread), are local to that thread 
only.  The C<useit> merely ensures that the effective C<use> is done at 
execution time, rather than at compile time.  And if you place a C<useit 
Module> inside a thread, then the Module will be C<require>d and its import 
executed inside the thread only.  And when the thread ends, everything that 
was that thread, including the newly loaded module, will be gone again.


>(BTW your module doesn't provide an interface equivalent to
>         use Foo ();
>         no Bar ();
>--that doesn't call import().)

Indeed.  Is there a way to find out whether a subroutine is called without 
any parameters or with an empty list?  Cause when I can do that, I can 
simulate this behaviour as well...


Liz




nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About