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