78d328e132add1a64cfed24b93e15409cb9ac976
[p5sagit/p5-mst-13.2.git] / ext / threads / threads.pm
1 package threads;
2
3 use 5.008;
4 use strict;
5 use warnings;
6 use Config;
7
8 BEGIN {
9     unless ($Config{useithreads}) {
10         my @caller = caller(2);
11         die <<EOF;
12 $caller[1] line $caller[2]:
13
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.)
16
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.)
21
22 If you want to the use the threads module, please contact the people
23 who built your Perl.
24
25 Cannot continue, aborting.
26 EOF
27     }
28 }
29
30 use overload
31     '==' => \&equal,
32     'fallback' => 1;
33
34 BEGIN {
35     warn "Warning, threads::shared has already been loaded. ".
36        "To enable shared variables for these modules 'use threads' ".
37        "must be called before any of those modules are loaded\n"
38                if($threads::shared::threads_shared);
39 }
40
41 our $VERSION = '1.18';
42
43
44 # Load the XS code
45 require XSLoader;
46 XSLoader::load('threads', $VERSION);
47
48
49 ### Export ###
50
51 sub import
52 {
53     my $class = shift;   # Not used
54
55     # Exported subroutines
56     my @EXPORT = qw(async);
57
58     # Handle args
59     while (my $sym = shift) {
60         if ($sym =~ /all/) {
61             push(@EXPORT, qw(yield));
62
63         } else {
64             push(@EXPORT, $sym);
65         }
66     }
67
68     # Export subroutine names
69     my $caller = caller();
70     foreach my $sym (@EXPORT) {
71         no strict 'refs';
72         *{$caller.'::'.$sym} = \&{$sym};
73     }
74 }
75
76
77 ### Methods, etc. ###
78
79 # use "goto" trick to avoid pad problems from 5.8.1 (fixed in 5.8.2)
80 # should also be faster
81 sub async (&;@) { unshift @_,'threads'; goto &new }
82
83 $threads::threads = 1;
84
85 # 'new' is an alias for 'create'
86 *new = \&create;
87
88 1;
89
90 __END__
91
92 =head1 NAME
93
94 threads - Perl interpreter-based threads
95
96 =head1 VERSION
97
98 This document describes threads version 1.18
99
100 =head1 SYNOPSIS
101
102     use threads ('yield');
103
104     sub start_thread {
105         my @args = @_;
106         print "Thread started: @args\n";
107     }
108     my $thread = threads->create('start_thread', 'argument');
109     $thread->join();
110
111     threads->create(sub { print("I am a thread\n"); })->join();
112
113     my $thread3 = async { foreach (@files) { ... } };
114     $thread3->join();
115
116     # Invoke thread in list context so it can return a list
117     my ($thr) = threads->create(sub { return (qw/a b c/); });
118     my @results = $thr->join();
119
120     $thread->detach();
121
122     $thread = threads->self();
123     $thread = threads->object($tid);
124
125     $tid = threads->tid();
126     $tid = threads->self->tid();
127     $tid = $thread->tid();
128
129     threads->yield();
130     yield();
131
132     my @threads = threads->list();
133
134     if ($thr1 == $thr2) {
135         ...
136     }
137
138 =head1 DESCRIPTION
139
140 Perl 5.6 introduced something called interpreter threads.  Interpreter
141 threads are different from "5005threads" (the thread model of Perl
142 5.005) by creating a new perl interpreter per thread and not sharing
143 any data or state between threads by default.
144
145 Prior to perl 5.8 this has only been available to people embedding
146 perl and for emulating fork() on windows.
147
148 The threads API is loosely based on the old Thread.pm API. It is very
149 important to note that variables are not shared between threads, all
150 variables are per default thread local.  To use shared variables one
151 must use threads::shared.
152
153 It is also important to note that you must enable threads by doing
154 C<use threads> as early as possible in the script itself and that it
155 is not possible to enable threading inside an C<eval "">, C<do>,
156 C<require>, or C<use>.  In particular, if you are intending to share
157 variables with threads::shared, you must C<use threads> before you
158 C<use threads::shared> and C<threads> will emit a warning if you do
159 it the other way around.
160
161 =over
162
163 =item $thr = threads->create(FUNCTION, ARGS)
164
165 This will create a new thread that will begin execution with the specified
166 entry point function, and give it the I<ARGS> list as parameters.  It will
167 return the corresponding threads object, or C<undef> if thread creation failed.
168
169 I<FUNCTION> may either be the name of a function, an anonymous subroutine, or
170 a code ref.
171
172     my $thr = threads->create('func_name', ...);
173         # or
174     my $thr = threads->create(sub { ... }, ...);
175         # or
176     my $thr = threads->create(\&func, ...);
177
178 The thread may be created in I<list> context, or I<scalar> context as follows:
179
180     # Create thread in list context
181     my ($thr) = threads->create(...);
182
183     # Create thread in scalar context
184     my $thr = threads->create(...);
185
186 This has consequences for the C<-E<gt>join()> method describe below.
187
188 Although a thread may be created in I<void> context, to do so you must
189 I<chain> either the C<-E<gt>join()> or C<-E<gt>detach()> method to the
190 C<-E<gt>create()> call:
191
192     threads->create(...)->join();
193
194 The C<-E<gt>new()> method is an alias for C<-E<gt>create()>.
195
196 =item $thr->join()
197
198 This will wait for the corresponding thread to complete its execution.  When
199 the thread finishes, C<-E<gt>join()> will return the return value(s) of the
200 entry point function.
201
202 The context (void, scalar or list) of the thread creation is also the
203 context for C<-E<gt>join()>.  This means that if you intend to return an array
204 from a thread, you must use C<my ($thr) = threads->create(...)>, and that
205 if you intend to return a scalar, you must use C<my $thr = ...>:
206
207     # Create thread in list context
208     my ($thr1) = threads->create(sub {
209                                     my @results = qw(a b c);
210                                     return (@results);
211                                  };
212     # Retrieve list results from thread
213     my @res1 = $thr1->join();
214
215     # Create thread in scalar context
216     my $thr2 = threads->create(sub {
217                                     my $result = 42;
218                                     return ($result);
219                                  };
220     # Retrieve scalar result from thread
221     my $res2 = $thr2->join();
222
223 If the program exits without all other threads having been either joined or
224 detached, then a warning will be issued. (A program exits either because one
225 of its threads explicitly calls L<exit()|perlfunc/"exit EXPR">, or in the case
226 of the main thread, reaches the end of the main program file.)
227
228 =item $thread->detach
229
230 Will make the thread unjoinable, and cause any eventual return value
231 to be discarded.
232
233 Calling C<-E<gt>join()> on a detached thread will cause an error to be thrown.
234
235 =item threads->detach()
236
237 Class method that allows a thread to detach itself.
238
239 =item threads->self
240
241 This will return the thread object for the current thread.
242
243 =item $thr->tid()
244
245 Returns the ID of the thread.  Thread IDs are unique integers with the main
246 thread in a program being 0, and incrementing by 1 for every thread created.
247
248 =item threads->tid()
249
250 Class method that allows a thread to obtain its own ID.
251
252 =item threads->object($tid)
253
254 This will return the I<threads> object for the I<active> thread associated
255 with the specified thread ID.  Returns C<undef> if there is no thread
256 associated with the TID, if the thread is joined or detached, if no TID is
257 specified or if the specified TID is undef.
258
259 =item threads->yield();
260
261 This is a suggestion to the OS to let this thread yield CPU time to other
262 threads.  What actually happens is highly dependent upon the underlying
263 thread implementation.
264
265 You may do C<use threads qw(yield)> then use just a bare C<yield> in your
266 code.
267
268 =item threads->list()
269
270 In a list context, returns a list of all non-joined, non-detached I<threads>
271 objects.  In a scalar context, returns a count of the same.
272
273 =item $thr1->equal($thr2)
274
275 Tests if two threads objects are the same thread or not.  This is overloaded
276 to the more natural form:
277
278     if ($thr1 == $thr2) {
279         print("Threads are the same\n");
280     }
281
282 (Thread comparison is based on thread IDs.)
283
284 =item async BLOCK;
285
286 C<async> creates a thread to execute the block immediately following
287 it.  This block is treated as an anonymous sub, and so must have a
288 semi-colon after the closing brace. Like C<< threads->new >>, C<async>
289 returns a thread object.
290
291 =item $thr->_handle()
292
293 This I<private> method returns the memory location of the internal thread
294 structure associated with a threads object.  For Win32, this is the handle
295 returned by C<CreateThread>; for other platforms, it is the pointer returned
296 by C<pthread_create>.
297
298 This method is of no use for general Perl threads programming.  Its intent is
299 to provide other (XS-based) thread modules with the capability to access, and
300 possibly manipulate, the underlying thread structure associated with a Perl
301 thread.
302
303 =item threads->_handle()
304
305 Class method that allows a thread to obtain its own I<handle>.
306
307 =back
308
309 =head1 WARNINGS
310
311 =over 4
312
313 =item A thread exited while %d other threads were still running
314
315 A thread (not necessarily the main thread) exited while there were
316 still other threads running.  Usually it's a good idea to first collect
317 the return values of the created threads by joining them, and only then
318 exit from the main thread.
319
320 =back
321
322 =head1 ERRORS
323
324 =over 4
325
326 =item This Perl hasn't been configured and built properly for the threads...
327
328 The particular copy of Perl that you're trying to use was not built using the
329 C<useithreads> configuration option.
330
331 Having threads support requires all of Perl and all of the XS modules in the
332 Perl installation to be rebuilt; it is not just a question of adding the
333 L<threads> module (i.e., threaded and non-threaded Perls are binary
334 incompatible.)
335
336 =back
337
338 =head1 BUGS
339
340 =over
341
342 =item Parent-Child threads.
343
344 On some platforms it might not be possible to destroy "parent"
345 threads while there are still existing child "threads".
346
347 =item Creating threads inside BEGIN blocks
348
349 Creating threads inside BEGIN blocks (or during the compilation phase
350 in general) does not work.  (In Windows, trying to use fork() inside
351 BEGIN blocks is an equally losing proposition, since it has been
352 implemented in very much the same way as threads.)
353
354 =item PERL_OLD_SIGNALS are not threadsafe, will not be.
355
356 If your Perl has been built with PERL_OLD_SIGNALS (one has
357 to explicitly add that symbol to ccflags, see C<perl -V>),
358 signal handling is not threadsafe.
359
360 =item Returning closures from threads
361
362 Returning a closure from a thread does not work, usually crashing Perl in the
363 process.
364
365 =item Perl Bugs and the CPAN Version of L<threads>
366
367 Support for threads extents beyond the code in this module (i.e.,
368 F<threads.pm> and F<threads.xs>), and into the Perl iterpreter itself.  Older
369 versions of Perl contain bugs that may manifest themselves despite using the
370 latest version of L<threads> from CPAN.  There is no workaround for this other
371 than upgrading to the lastest version of Perl.
372
373 (Before you consider posting a bug report, please consult, and possibly post a
374 message to the discussion forum to see if what you've encountered is a known
375 problem.)
376
377 =back
378
379 =head1 REQUIREMENTS
380
381 Perl 5.8.0 or later
382
383 =head1 SEE ALSO
384
385 L<threads> Discussion Forum on CPAN:
386 L<http://www.cpanforum.com/dist/threads>
387
388 Annotated POD for L<threads>:
389 L<http://annocpan.org/~JDHEDDEN/threads-1.18/shared.pm>
390
391 L<threads::shared>, L<perlthrtut>
392
393 L<http://www.perl.com/pub/a/2002/06/11/threads.html> and
394 L<http://www.perl.com/pub/a/2002/09/04/threads.html>
395
396 Perl threads mailing list:
397 L<http://lists.cpan.org/showlist.cgi?name=iThreads>
398
399 =head1 AUTHOR
400
401 Artur Bergman E<lt>sky AT crucially DOT netE<gt>
402
403 threads is released under the same license as Perl.
404
405 CPAN version produced by Jerry D. Hedden <jdhedden AT cpan DOT org>
406
407 =head1 ACKNOWLEDGEMENTS
408
409 Richard Soderberg E<lt>perl AT crystalflame DOT netE<gt> -
410 Helping me out tons, trying to find reasons for races and other weird bugs!
411
412 Simon Cozens E<lt>simon AT brecon DOT co DOT ukE<gt> -
413 Being there to answer zillions of annoying questions
414
415 Rocco Caputo E<lt>troc AT netrus DOT netE<gt>
416
417 Vipul Ved Prakash E<lt>mail AT vipul DOT netE<gt> -
418 Helping with debugging
419
420 =cut