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