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