9 unless ($Config{useithreads}) {
10 my @caller = caller(2);
12 $caller[1] line $caller[2]:
14 This Perl hasn't been configured and built properly for the threads
15 module to work. (The 'useithreads' configuration option hasn't been used.)
17 Having threads support requires all of Perl and all of the XS modules in
18 the Perl installation to be rebuilt, it is not just a question of adding
19 the threads module. (In other words, threaded and non-threaded Perls
20 are binary incompatible.)
22 If you want to the use the threads module, please contact the people
25 Cannot continue, aborting.
32 '!=' => sub { !equal(@_) },
36 warn "Warning, threads::shared has already been loaded. ".
37 "To enable shared variables for these modules 'use threads' ".
38 "must be called before any of those modules are loaded\n"
39 if($threads::shared::threads_shared);
42 our $VERSION = '1.18_03';
47 XSLoader::load('threads', $VERSION);
54 my $class = shift; # Not used
56 # Exported subroutines
57 my @EXPORT = qw(async);
60 while (my $sym = shift) {
62 push(@EXPORT, qw(yield));
69 # Export subroutine names
70 my $caller = caller();
71 foreach my $sym (@EXPORT) {
73 *{$caller.'::'.$sym} = \&{$sym};
80 # use "goto" trick to avoid pad problems from 5.8.1 (fixed in 5.8.2)
81 # should also be faster
82 sub async (&;@) { unshift @_,'threads'; goto &new }
84 $threads::threads = 1;
86 # 'new' is an alias for 'create'
95 threads - Perl interpreter-based threads
99 This document describes threads version 1.18
103 use threads ('yield');
107 print "Thread started: @args\n";
109 my $thread = threads->create('start_thread', 'argument');
112 threads->create(sub { print("I am a thread\n"); })->join();
114 my $thread3 = async { foreach (@files) { ... } };
117 # Invoke thread in list context so it can return a list
118 my ($thr) = threads->create(sub { return (qw/a b c/); });
119 my @results = $thr->join();
123 $thread = threads->self();
124 $thread = threads->object($tid);
126 $tid = threads->tid();
127 $tid = threads->self->tid();
128 $tid = $thread->tid();
133 my @threads = threads->list();
135 if ($thr1 == $thr2) {
141 Perl 5.6 introduced something called interpreter threads. Interpreter
142 threads are different from "5005threads" (the thread model of Perl
143 5.005) by creating a new perl interpreter per thread and not sharing
144 any data or state between threads by default.
146 Prior to perl 5.8 this has only been available to people embedding
147 perl and for emulating fork() on windows.
149 The threads API is loosely based on the old Thread.pm API. It is very
150 important to note that variables are not shared between threads, all
151 variables are per default thread local. To use shared variables one
152 must use threads::shared.
154 It is also important to note that you must enable threads by doing
155 C<use threads> as early as possible in the script itself and that it
156 is not possible to enable threading inside an C<eval "">, C<do>,
157 C<require>, or C<use>. In particular, if you are intending to share
158 variables with threads::shared, you must C<use threads> before you
159 C<use threads::shared> and C<threads> will emit a warning if you do
160 it the other way around.
164 =item $thr = threads->create(FUNCTION, ARGS)
166 This will create a new thread that will begin execution with the specified
167 entry point function, and give it the I<ARGS> list as parameters. It will
168 return the corresponding threads object, or C<undef> if thread creation failed.
170 I<FUNCTION> may either be the name of a function, an anonymous subroutine, or
173 my $thr = threads->create('func_name', ...);
175 my $thr = threads->create(sub { ... }, ...);
177 my $thr = threads->create(\&func, ...);
179 The thread may be created in I<list> context, or I<scalar> context as follows:
181 # Create thread in list context
182 my ($thr) = threads->create(...);
184 # Create thread in scalar context
185 my $thr = threads->create(...);
187 This has consequences for the C<-E<gt>join()> method describe below.
189 Although a thread may be created in I<void> context, to do so you must
190 I<chain> either the C<-E<gt>join()> or C<-E<gt>detach()> method to the
191 C<-E<gt>create()> call:
193 threads->create(...)->join();
195 The C<-E<gt>new()> method is an alias for C<-E<gt>create()>.
199 This will wait for the corresponding thread to complete its execution. When
200 the thread finishes, C<-E<gt>join()> will return the return value(s) of the
201 entry point function.
203 The context (void, scalar or list) of the thread creation is also the
204 context for C<-E<gt>join()>. This means that if you intend to return an array
205 from a thread, you must use C<my ($thr) = threads->create(...)>, and that
206 if you intend to return a scalar, you must use C<my $thr = ...>:
208 # Create thread in list context
209 my ($thr1) = threads->create(sub {
210 my @results = qw(a b c);
213 # Retrieve list results from thread
214 my @res1 = $thr1->join();
216 # Create thread in scalar context
217 my $thr2 = threads->create(sub {
221 # Retrieve scalar result from thread
222 my $res2 = $thr2->join();
224 If the program exits without all other threads having been either joined or
225 detached, then a warning will be issued. (A program exits either because one
226 of its threads explicitly calls L<exit()|perlfunc/"exit EXPR">, or in the case
227 of the main thread, reaches the end of the main program file.)
229 =item $thread->detach
231 Will make the thread unjoinable, and cause any eventual return value
234 Calling C<-E<gt>join()> on a detached thread will cause an error to be thrown.
236 =item threads->detach()
238 Class method that allows a thread to detach itself.
242 This will return the thread object for the current thread.
246 Returns the ID of the thread. Thread IDs are unique integers with the main
247 thread in a program being 0, and incrementing by 1 for every thread created.
251 Class method that allows a thread to obtain its own ID.
253 =item threads->object($tid)
255 This will return the I<threads> object for the I<active> thread associated
256 with the specified thread ID. Returns C<undef> if there is no thread
257 associated with the TID, if the thread is joined or detached, if no TID is
258 specified or if the specified TID is undef.
260 =item threads->yield();
262 This is a suggestion to the OS to let this thread yield CPU time to other
263 threads. What actually happens is highly dependent upon the underlying
264 thread implementation.
266 You may do C<use threads qw(yield)> then use just a bare C<yield> in your
269 =item threads->list()
271 In a list context, returns a list of all non-joined, non-detached I<threads>
272 objects. In a scalar context, returns a count of the same.
274 =item $thr1->equal($thr2)
276 Tests if two threads objects are the same thread or not. This is overloaded
277 to the more natural form:
279 if ($thr1 == $thr2) {
280 print("Threads are the same\n");
283 (Thread comparison is based on thread IDs.)
287 C<async> creates a thread to execute the block immediately following
288 it. This block is treated as an anonymous sub, and so must have a
289 semi-colon after the closing brace. Like C<< threads->new >>, C<async>
290 returns a thread object.
292 =item $thr->_handle()
294 This I<private> method returns the memory location of the internal thread
295 structure associated with a threads object. For Win32, this is the handle
296 returned by C<CreateThread>; for other platforms, it is the pointer returned
297 by C<pthread_create>.
299 This method is of no use for general Perl threads programming. Its intent is
300 to provide other (XS-based) thread modules with the capability to access, and
301 possibly manipulate, the underlying thread structure associated with a Perl
304 =item threads->_handle()
306 Class method that allows a thread to obtain its own I<handle>.
314 =item A thread exited while %d other threads were still running
316 A thread (not necessarily the main thread) exited while there were
317 still other threads running. Usually it's a good idea to first collect
318 the return values of the created threads by joining them, and only then
319 exit from the main thread.
327 =item This Perl hasn't been configured and built properly for the threads...
329 The particular copy of Perl that you're trying to use was not built using the
330 C<useithreads> configuration option.
332 Having threads support requires all of Perl and all of the XS modules in the
333 Perl installation to be rebuilt; it is not just a question of adding the
334 L<threads> module (i.e., threaded and non-threaded Perls are binary
343 =item Parent-Child threads.
345 On some platforms it might not be possible to destroy "parent"
346 threads while there are still existing child "threads".
348 =item Creating threads inside BEGIN blocks
350 Creating threads inside BEGIN blocks (or during the compilation phase
351 in general) does not work. (In Windows, trying to use fork() inside
352 BEGIN blocks is an equally losing proposition, since it has been
353 implemented in very much the same way as threads.)
355 =item PERL_OLD_SIGNALS are not threadsafe, will not be.
357 If your Perl has been built with PERL_OLD_SIGNALS (one has
358 to explicitly add that symbol to ccflags, see C<perl -V>),
359 signal handling is not threadsafe.
361 =item Returning closures from threads
363 Returning a closure from a thread does not work, usually crashing Perl in the
366 =item Perl Bugs and the CPAN Version of L<threads>
368 Support for threads extents beyond the code in this module (i.e.,
369 F<threads.pm> and F<threads.xs>), and into the Perl iterpreter itself. Older
370 versions of Perl contain bugs that may manifest themselves despite using the
371 latest version of L<threads> from CPAN. There is no workaround for this other
372 than upgrading to the lastest version of Perl.
374 (Before you consider posting a bug report, please consult, and possibly post a
375 message to the discussion forum to see if what you've encountered is a known
386 L<threads> Discussion Forum on CPAN:
387 L<http://www.cpanforum.com/dist/threads>
389 Annotated POD for L<threads>:
390 L<http://annocpan.org/~JDHEDDEN/threads-1.18/shared.pm>
392 L<threads::shared>, L<perlthrtut>
394 L<http://www.perl.com/pub/a/2002/06/11/threads.html> and
395 L<http://www.perl.com/pub/a/2002/09/04/threads.html>
397 Perl threads mailing list:
398 L<http://lists.cpan.org/showlist.cgi?name=iThreads>
402 Artur Bergman E<lt>sky AT crucially DOT netE<gt>
404 threads is released under the same license as Perl.
406 CPAN version produced by Jerry D. Hedden <jdhedden AT cpan DOT org>
408 =head1 ACKNOWLEDGEMENTS
410 Richard Soderberg E<lt>perl AT crystalflame DOT netE<gt> -
411 Helping me out tons, trying to find reasons for races and other weird bugs!
413 Simon Cozens E<lt>simon AT brecon DOT co DOT ukE<gt> -
414 Being there to answer zillions of annoying questions
416 Rocco Caputo E<lt>troc AT netrus DOT netE<gt>
418 Vipul Ved Prakash E<lt>mail AT vipul DOT netE<gt> -
419 Helping with debugging