| Thread-Use documentation | view source | Contained in the Thread-Use distribution. |
Thread::Use - use a module inside a thread only
use Thread::Use;
threads->new( sub {
useit Module;
useit Module qw(parameters);
noit Module;
noit Module qw(parameters);
} );
*** A note of CAUTION ***
This module only functions on Perl versions 5.8.0 and later.
And then only when threads are enabled with -Dusethreads. It
is of no use with any version of Perl before 5.8.0 or without
threads enabled.
*************************
When you are programming threaded applications and are interested in saving
memory by selectively loading modules inside threads only, you will find that
even if you use a module inside a thread, it is in fact available to all
threads, including the main thread.
This is caused by the fact that use is executed at compile time. At which
time Perl doesn't know anything about threads yet.
However, some modules, specifically the ones that are (partly) implemented
in XS, do not (yet) survive the cloning process that is involved with creating
threads. So you can only use these modules inside threads only. But if you
use a module, it will be read in at compile time.
Of course, a use is nothing more than a require followed by a call
to the "import" class routine (if available). But that doesn't feel natural
to do. So this module allows you to use the useit (for use in
threads command to indicate that a module should only be used inside
a thread.
For example: suppose you only need the PerlIO::gzip module inside a thread:
use Thread::Use; # can be anywhere in your program
threads->new( \&zipfile,filename,contents ); # start the thread
sub zipfile {
useit PerlIO::gzip; # only use inside this thread
open( my $out,'>:gzip', $_[0] ) or die "$_[0]: $!";
print $out $_[1];
close( $out );
}
For completeness, it is also possible to pass any parameters as you would
with the use command. So:
sub storable {
useit Storable qw(freeze); # export "freeze" to namespace of thread
my $frozen = freeze( \@_ );
}
or to use the opposite no equivalent;
sub warnings {
useit warnings "all";
# special code
noit warnings "all";
}
(none)
This modules is still experimental and subject to change. At the current stage it is more a proof of concept than anything else.
There is no way to useit a module without having it call the "import"
class method, as you can do with use Module (). However, a simple
require Module does exactly the same, so if you want to useit a module
without calling its "import" method, you should just use require.
Elizabeth Mattijsen, <liz@dijkmat.nl>.
Please report bugs to <perlbugs@dijkmat.nl>.
Copyright (c) 2002-2003 Elizabeth Mattijsen <liz@dijkmat.nl>. All rights reserved. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
| Thread-Use documentation | view source | Contained in the Thread-Use distribution. |