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