This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Upgrade to Devel::PPPort 3.08_07
[perl5.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.32';
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
34 # Load the XS code
35 require XSLoader;
36 XSLoader::load('threads', $XS_VERSION);
37
38
39 ### Export ###
40
41 sub 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 =~ /^stack/) {
51             threads->set_stack_size(shift);
52
53         } elsif ($sym =~ /all/) {
54             push(@EXPORT, qw(yield));
55
56         } else {
57             push(@EXPORT, $sym);
58         }
59     }
60
61     # Export subroutine names
62     my $caller = caller();
63     foreach my $sym (@EXPORT) {
64         no strict 'refs';
65         *{$caller.'::'.$sym} = \&{$sym};
66     }
67
68     # Set stack size via environment variable
69     if (exists($ENV{'PERL5_ITHREADS_STACK_SIZE'})) {
70         threads->set_stack_size($ENV{'PERL5_ITHREADS_STACK_SIZE'});
71     }
72 }
73
74
75 ### Methods, etc. ###
76
77 # 'new' is an alias for 'create'
78 *new = \&create;
79
80 # 'async' is a function alias for the 'threads->create()' method
81 sub async (&;@)
82 {
83     unshift(@_, 'threads');
84     # Use "goto" trick to avoid pad problems from 5.8.1 (fixed in 5.8.2)
85     goto &create;
86 }
87
88 # Thread object equality checking
89 use overload (
90     '==' => \&equal,
91     '!=' => sub { ! equal(@_) },
92     'fallback' => 1
93 );
94
95 1;
96
97 __END__
98
99 =head1 NAME
100
101 threads - Perl interpreter-based threads
102
103 =head1 VERSION
104
105 This document describes threads version 1.32
106
107 =head1 SYNOPSIS
108
109     use threads ('yield', 'stack_size' => 64*4096);
110
111     sub start_thread {
112         my @args = @_;
113         print('Thread started: ', join(' ', @args), "\n");
114     }
115     my $thread = threads->create('start_thread', 'argument');
116     $thread->join();
117
118     threads->create(sub { print("I am a thread\n"); })->join();
119
120     my $thread3 = async { foreach (@files) { ... } };
121     $thread3->join();
122
123     # Invoke thread in list context (implicit) so it can return a list
124     my ($thr) = threads->create(sub { return (qw/a b c/); });
125     # or specify list context explicitly
126     my $thr = threads->create({'context' => 'list'},
127                               sub { return (qw/a b c/); });
128     my @results = $thr->join();
129
130     $thread->detach();
131
132     $thread = threads->self();
133     $thread = threads->object($tid);
134
135     $tid = threads->tid();
136     $tid = threads->self->tid();
137     $tid = $thread->tid();
138
139     threads->yield();
140     yield();
141
142     my @threads = threads->list();
143     my $thread_count = threads->list();
144
145     if ($thr1 == $thr2) {
146         ...
147     }
148
149     $stack_size = threads->get_stack_size();
150     $old_size = threads->set_stack_size(32*4096);
151
152     # Create a thread with a specific context and stack size
153     my $thr = threads->create({ 'context'    => 'list',
154                                 'stack_size' => 32*4096 },
155                               \&foo);
156     my @results = $thr->join();
157
158     $thr->kill('SIGUSR1');
159
160 =head1 DESCRIPTION
161
162 Perl 5.6 introduced something called interpreter threads.  Interpreter threads
163 are different from I<5005threads> (the thread model of Perl 5.005) by creating
164 a new Perl interpreter per thread, and not sharing any data or state between
165 threads by default.
166
167 Prior to Perl 5.8, this has only been available to people embedding Perl, and
168 for emulating fork() on Windows.
169
170 The I<threads> API is loosely based on the old Thread.pm API. It is very
171 important to note that variables are not shared between threads, all variables
172 are by default thread local.  To use shared variables one must use
173 L<threads::shared>.
174
175 It is also important to note that you must enable threads by doing C<use
176 threads> as early as possible in the script itself, and that it is not
177 possible to enable threading inside an C<eval "">, C<do>, C<require>, or
178 C<use>.  In particular, if you are intending to share variables with
179 L<threads::shared>, you must C<use threads> before you C<use threads::shared>.
180 (C<threads> will emit a warning if you do it the other way around.)
181
182 =over
183
184 =item $thr = threads->create(FUNCTION, ARGS)
185
186 This will create a new thread that will begin execution with the specified
187 entry point function, and give it the I<ARGS> list as parameters.  It will
188 return the corresponding threads object, or C<undef> if thread creation failed.
189
190 I<FUNCTION> may either be the name of a function, an anonymous subroutine, or
191 a code ref.
192
193     my $thr = threads->create('func_name', ...);
194         # or
195     my $thr = threads->create(sub { ... }, ...);
196         # or
197     my $thr = threads->create(\&func, ...);
198
199 The C<-E<gt>new()> method is an alias for C<-E<gt>create()>.
200
201 =item $thr->join()
202
203 This will wait for the corresponding thread to complete its execution.  When
204 the thread finishes, C<-E<gt>join()> will return the return value(s) of the
205 entry point function.
206
207 The context (void, scalar or list) for the return value(s) for C<-E<gt>join()>
208 is determined at the time of thread creation.
209
210     # Create thread in list context (implicit)
211     my ($thr1) = threads->create(sub {
212                                     my @results = qw(a b c);
213                                     return (@results);
214                                  });
215     #   or (explicit)
216     my $thr1 = threads->create({'context' => 'list'},
217                                sub {
218                                     my @results = qw(a b c);
219                                     return (@results);
220                                });
221     # Retrieve list results from thread
222     my @res1 = $thr1->join();
223
224     # Create thread in scalar context (implicit)
225     my $thr2 = threads->create(sub {
226                                     my $result = 42;
227                                     return ($result);
228                                  });
229     # Retrieve scalar result from thread
230     my $res2 = $thr2->join();
231
232     # Create a thread in void context (explicit)
233     my $thr3 = threads->create({'void' => 1},
234                                sub { print("Hello, world\n"); });
235     # Join the thread in void context (i.e., no return value)
236     $thr3->join();
237
238 See L</"THREAD CONTEXT"> for more details.
239
240 If the program exits without all other threads having been either joined or
241 detached, then a warning will be issued. (A program exits either because one
242 of its threads explicitly calls L<exit()|perlfunc/"exit EXPR">, or in the case
243 of the main thread, reaches the end of the main program file.)
244
245 Calling C<-E<gt>join()> or C<-E<gt>detach()> on an already joined thread will
246 cause an error to be thrown.
247
248 =item $thr->detach()
249
250 Makes the thread unjoinable, and causes any eventual return value to be
251 discarded.
252
253 Calling C<-E<gt>join()> or C<-E<gt>detach()> on an already detached thread
254 will cause an error to be thrown.
255
256 =item threads->detach()
257
258 Class method that allows a thread to detach itself.
259
260 =item threads->self()
261
262 Class method that allows a thread to obtain its own I<threads> object.
263
264 =item $thr->tid()
265
266 Returns the ID of the thread.  Thread IDs are unique integers with the main
267 thread in a program being 0, and incrementing by 1 for every thread created.
268
269 =item threads->tid()
270
271 Class method that allows a thread to obtain its own ID.
272
273 =item threads->object($tid)
274
275 This will return the I<threads> object for the I<active> thread associated
276 with the specified thread ID.  Returns C<undef> if there is no thread
277 associated with the TID, if the thread is joined or detached, if no TID is
278 specified or if the specified TID is undef.
279
280 =item threads->yield()
281
282 This is a suggestion to the OS to let this thread yield CPU time to other
283 threads.  What actually happens is highly dependent upon the underlying
284 thread implementation.
285
286 You may do C<use threads qw(yield)>, and then just use C<yield()> in your
287 code.
288
289 =item threads->list()
290
291 In a list context, returns a list of all non-joined, non-detached I<threads>
292 objects.  In a scalar context, returns a count of the same.
293
294 =item $thr1->equal($thr2)
295
296 Tests if two threads objects are the same thread or not.  This is overloaded
297 to the more natural forms:
298
299     if ($thr1 == $thr2) {
300         print("Threads are the same\n");
301     }
302     # or
303     if ($thr1 != $thr2) {
304         print("Threads differ\n");
305     }
306
307 (Thread comparison is based on thread IDs.)
308
309 =item async BLOCK;
310
311 C<async> creates a thread to execute the block immediately following
312 it.  This block is treated as an anonymous subroutine, and so must have a
313 semi-colon after the closing brace.  Like C<threads->create()>, C<async>
314 returns a I<threads> object.
315
316 =item $thr->_handle()
317
318 This I<private> method returns the memory location of the internal thread
319 structure associated with a threads object.  For Win32, this is a pointer to
320 the C<HANDLE> value returned by C<CreateThread> (i.e., C<HANDLE *>); for other
321 platforms, it is a pointer to the C<pthread_t> structure used in the
322 C<pthread_create> call (i.e., C<pthread_t *>).
323
324 This method is of no use for general Perl threads programming.  Its intent is
325 to provide other (XS-based) thread modules with the capability to access, and
326 possibly manipulate, the underlying thread structure associated with a Perl
327 thread.
328
329 =item threads->_handle()
330
331 Class method that allows a thread to obtain its own I<handle>.
332
333 =back
334
335 =head1 THREAD CONTEXT
336
337 As with subroutines, the type of value returned from a thread's entry point
338 function may be determined by the thread's I<context>:  list, scalar or void.
339 The thread's context is determined at thread creation.  This is necessary so
340 that the context is available to the entry point function via
341 L<wantarray()|perlfunc/"wantarray">.  The thread may then specify a value of
342 the appropriate type to be returned from C<-E<gt>join()>.
343
344 =head2 Explicit context
345
346 Because thread creation and thread joining may occur in different contexts, it
347 may be desirable to state the context explicitly to the thread's entry point
348 function.  This may be done by calling C<-E<gt>create()> with a parameter hash
349 as the first argument:
350
351     my $thr = threads->create({'context' => 'list'}, \&foo);
352     ...
353     my @results = $thr->join();
354
355 In the above, the threads object is returned to the parent thread in scalar
356 context, and the thread's entry point function C<foo> will be called in list
357 context such that the parent thread can receive a list from the C<-E<gt>join()>
358 call.  Similarly, if you need the threads object, but your thread will not be
359 returning a value (i.e., I<void> context), you would do the following:
360
361     my $thr = threads->create({'context' => 'void'}, \&foo);
362     ...
363     $thr->join();
364
365 The context type may also be used as the I<key> in the parameter hash followed
366 by a I<true> value:
367
368     threads->create({'scalar' => 1}, \&foo);
369     ...
370     my ($thr) = threads->list();
371     my $result = $thr->join();
372
373 =head2 Implicit context
374
375 If not explicitly stated, the thread's context is implied from the context
376 of the C<-E<gt>create()> call:
377
378     # Create thread in list context
379     my ($thr) = threads->create(...);
380
381     # Create thread in scalar context
382     my $thr = threads->create(...);
383
384     # Create thread in void context
385     threads->create(...);
386
387 =head1 THREAD STACK SIZE
388
389 The default per-thread stack size for different platforms varies
390 significantly, and is almost always far more than is needed for most
391 applications.  On Win32, Perl's makefile explicitly sets the default stack to
392 16 MB; on most other platforms, the system default is used, which again may be
393 much larger than is needed.
394
395 By tuning the stack size to more accurately reflect your application's needs,
396 you may significantly reduce your application's memory usage, and increase the
397 number of simultaneously running threads.
398
399 N.B., on Windows, Address space allocation granularity is 64 KB, therefore,
400 setting the stack smaller than that on Win32 Perl will not save any more
401 memory.
402
403 =over
404
405 =item threads->get_stack_size();
406
407 Returns the current default per-thread stack size.  The default is zero, which
408 means the system default stack size is currently in use.
409
410 =item $size = $thr->get_stack_size();
411
412 Returns the stack size for a particular thread.  A return value of zero
413 indicates the system default stack size was used for the thread.
414
415 =item $old_size = threads->set_stack_size($new_size);
416
417 Sets a new default per-thread stack size, and returns the previous setting.
418
419 Some platforms have a minimum thread stack size.  Trying to set the stack size
420 below this value will result in a warning, and the minimum stack size will be
421 used.
422
423 Some Linux platforms have a maximum stack size.  Setting too large of a stack
424 size will cause thread creation to fail.
425
426 If needed, C<$new_size> will be rounded up to the next multiple of the memory
427 page size (usually 4096 or 8192).
428
429 Threads created after the stack size is set will then either call
430 C<pthread_attr_setstacksize()> I<(for pthreads platforms)>, or supply the
431 stack size to C<CreateThread()> I<(for Win32 Perl)>.
432
433 (Obviously, this call does not affect any currently extant threads.)
434
435 =item use threads ('stack_size' => VALUE);
436
437 This sets the default per-thread stack size at the start of the application.
438
439 =item $ENV{'PERL5_ITHREADS_STACK_SIZE'}
440
441 The default per-thread stack size may be set at the start of the application
442 through the use of the environment variable C<PERL5_ITHREADS_STACK_SIZE>:
443
444     PERL5_ITHREADS_STACK_SIZE=1048576
445     export PERL5_ITHREADS_STACK_SIZE
446     perl -e'use threads; print(threads->get_stack_size(), "\n")'
447
448 This value overrides any C<stack_size> parameter given to C<use threads>.  Its
449 primary purpose is to permit setting the per-thread stack size for legacy
450 threaded applications.
451
452 =item threads->create({'stack_size' => VALUE}, FUNCTION, ARGS)
453
454 The stack size an individual threads may also be specified.  This may be done
455 by calling C<-E<gt>create()> with a parameter hash as the first argument:
456
457     my $thr = threads->create({'stack_size' => 32*4096}, \&foo, @args);
458
459 =item $thr2 = $thr1->create(FUNCTION, ARGS)
460
461 This creates a new thread (C<$thr2>) that inherits the stack size from an
462 existing thread (C<$thr1>).  This is shorthand for the following:
463
464     my $stack_size = $thr1->get_stack_size();
465     my $thr2 = threads->create({'stack_size' => $stack_size}, FUNCTION, ARGS);
466
467 =back
468
469 =head1 THREAD SIGNALLING
470
471 When safe signals is in effect (the default behavior - see L</"Unsafe signals">
472 for more details), then signals may be sent and acted upon by individual
473 threads.
474
475 =over 4
476
477 =item $thr->kill('SIG...');
478
479 Sends the specified signal to the thread.  Signal names and (positive) signal
480 numbers are the same as those supported by
481 L<kill()|perlfunc/"kill SIGNAL, LIST">.  For example, 'SIGTERM', 'TERM' and
482 (depending on the OS) 15 are all valid arguments to C<-E<gt>kill()>.
483
484 Returns the thread object to allow for method chaining:
485
486     $thr->kill('SIG...')->join();
487
488 =back
489
490 Signal handlers need to be set up in the threads for the signals they are
491 expected to act upon.  Here's an example for I<cancelling> a thread:
492
493     use threads;
494
495     # Suppress warning message when thread is 'killed'
496     no warnings 'threads';
497
498     sub thr_func
499     {
500         # Thread 'cancellation' signal handler
501         $SIG{'KILL'} = sub { die("Thread killed\n"); };
502
503         ...
504     }
505
506     # Create a thread
507     my $thr = threads->create('thr_func');
508
509     ...
510
511     # Signal the thread to terminate, and then detach
512     # it so that it will get cleaned up automatically
513     $thr->kill('KILL')->detach();
514
515 Here's another simplistic example that illustrates the use of thread
516 signalling in conjunction with a semaphore to provide rudimentary I<suspend>
517 and I<resume> capabilities:
518
519     use threads;
520     use Thread::Semaphore;
521
522     sub thr_func
523     {
524         my $sema = shift;
525
526         # Thread 'suspend/resume' signal handler
527         $SIG{'STOP'} = sub {
528             $sema->down();      # Thread suspended
529             $sema->up();        # Thread resumes
530         };
531
532         ...
533     }
534
535     # Create a semaphore and send it to a thread
536     my $sema = Thread::Semaphore->new();
537     my $thr = threads->create('thr_func', $sema);
538
539     # Suspend the thread
540     $sema->down();
541     $thr->kill('STOP');
542
543     ...
544
545     # Allow the thread to continue
546     $sema->up();
547
548 CAVEAT:  The thread signalling capability provided by this module does not
549 actually send signals via the OS.  It I<emulates> signals at the Perl-level
550 such that signal handlers are called in the appropriate thread.  For example,
551 sending C<$thr-E<gt>kill('STOP')> does not actually suspend a thread (or the
552 whole process), but does cause a C<$SIG{'STOP'}> handler to be called in that
553 thread (as illustrated above).
554
555 As such, signals that would normally not be appropriate to use in the
556 C<kill()> command (e.g., C<kill('KILL', $$)>) are okay to use with the
557 C<-E<gt>kill()> method (again, as illustrated above).
558
559 Correspondingly, sending a signal to a thread does not disrupt the operation
560 the thread is currently working on:  The signal will be acted upon after the
561 current operation has completed.  For instance, if the thread is I<stuck> on
562 an I/O call, sending it a signal will not cause the I/O call to be interrupted
563 such that the signal is acted up immediately.
564
565 =head1 WARNINGS
566
567 =over 4
568
569 =item A thread exited while # other threads were still running
570
571 A thread (not necessarily the main thread) exited while there were still other
572 threads running.  Usually, it's a good idea to first collect the return values
573 of the created threads by joining them, and only then exit from the main
574 thread.
575
576 =item Thread creation failed: pthread_create returned #
577
578 See the appropriate I<man> page for C<pthread_create> to determine the actual
579 cause for the failure.
580
581 =item Thread # terminated abnormally: ...
582
583 A thread terminated in some manner other than just returning from its entry
584 point function.  For example, the thread may have exited via C<die>.
585
586 =item Using minimum thread stack size of #
587
588 Some platforms have a minimum thread stack size.  Trying to set the stack size
589 below this value will result in the above warning, and the stack size will be
590 set to the minimum.
591
592 =item Thread creation failed: pthread_attr_setstacksize(I<SIZE>) returned 22
593
594 The specified I<SIZE> exceeds the system's maximum stack size.  Use a smaller
595 value for the stack size.
596
597 =back
598
599 If needed, thread warnings can be suppressed by using:
600
601     no warnings 'threads';
602
603 in the appropriate scope.
604
605 =head1 ERRORS
606
607 =over 4
608
609 =item This Perl not built to support threads
610
611 The particular copy of Perl that you're trying to use was not built using the
612 C<useithreads> configuration option.
613
614 Having threads support requires all of Perl and all of the XS modules in the
615 Perl installation to be rebuilt; it is not just a question of adding the
616 L<threads> module (i.e., threaded and non-threaded Perls are binary
617 incompatible.)
618
619 =item Cannot change stack size of an existing thread
620
621 The stack size of currently extant threads cannot be changed, therefore, the
622 following results in the above error:
623
624     $thr->set_stack_size($size);
625
626 =item Cannot signal other threads without safe signals
627
628 Safe signals must be in effect to use the C<-E<gt>kill()> signalling method.
629 See L</"Unsafe signals"> for more details.
630
631 =item Unrecognized signal name: ...
632
633 The particular copy of Perl that you're trying to use does not support the
634 specified signal being used in a C<-E<gt>kill()> call.
635
636 =back
637
638 =head1 BUGS
639
640 =over
641
642 =item Parent-child threads
643
644 On some platforms, it might not be possible to destroy I<parent> threads while
645 there are still existing I<child> threads.
646
647 =item Creating threads inside special blocks
648
649 Creating threads inside C<BEGIN>, C<CHECK> or C<INIT> blocks should not be
650 relied upon.  Depending on the Perl version and the application code, results
651 may range from success, to (apparently harmless) warnings of leaked scalar, or
652 all the way up to crashing of the Perl interpreter.
653
654 =item Unsafe signals
655
656 Since Perl 5.8.0, signals have been made safer in Perl by postponing their
657 handling until the interpreter is in a I<safe> state.  See
658 L<perl58delta/"Safe Signals"> and L<perlipc/"Deferred Signals (Safe Signals)">
659 for more details.
660
661 Safe signals is the default behavior, and the old, immediate, unsafe
662 signalling behavior is only in effect in the following situations:
663
664 =over 4
665
666 =item * Perl was been built with C<PERL_OLD_SIGNALS> (see C<perl -V>).
667
668 =item * The environment variable C<PERL_SIGNALS> is set to C<unsafe> (see L<perlrun/"PERL_SIGNALS">).
669
670 =item * The module L<Perl::Unsafe::Signals> is used.
671
672 =back
673
674 If unsafe signals is in effect, then signal handling is not thread-safe, and
675 the C<-E<gt>kill()> signalling method cannot be used.
676
677 =item Returning closures from threads
678
679 Returning closures from threads should not be relied upon.  Depending of the
680 Perl version and the application code, results may range from success, to
681 (apparently harmless) warnings of leaked scalar, or all the way up to crashing
682 of the Perl interpreter.
683
684 =item Perl Bugs and the CPAN Version of L<threads>
685
686 Support for threads extents beyond the code in this module (i.e.,
687 F<threads.pm> and F<threads.xs>), and into the Perl iterpreter itself.  Older
688 versions of Perl contain bugs that may manifest themselves despite using the
689 latest version of L<threads> from CPAN.  There is no workaround for this other
690 than upgrading to the lastest version of Perl.
691
692 (Before you consider posting a bug report, please consult, and possibly post a
693 message to the discussion forum to see if what you've encountered is a known
694 problem.)
695
696 =back
697
698 =head1 REQUIREMENTS
699
700 Perl 5.8.0 or later
701
702 =head1 SEE ALSO
703
704 L<threads> Discussion Forum on CPAN:
705 L<http://www.cpanforum.com/dist/threads>
706
707 Annotated POD for L<threads>:
708 L<http://annocpan.org/~JDHEDDEN/threads-1.32/shared.pm>
709
710 L<threads::shared>, L<perlthrtut>
711
712 L<http://www.perl.com/pub/a/2002/06/11/threads.html> and
713 L<http://www.perl.com/pub/a/2002/09/04/threads.html>
714
715 Perl threads mailing list:
716 L<http://lists.cpan.org/showlist.cgi?name=iThreads>
717
718 Stack size discussion:
719 L<http://www.perlmonks.org/?node_id=532956>
720
721 =head1 AUTHOR
722
723 Artur Bergman E<lt>sky AT crucially DOT netE<gt>
724
725 threads is released under the same license as Perl.
726
727 CPAN version produced by Jerry D. Hedden <jdhedden AT cpan DOT org>
728
729 =head1 ACKNOWLEDGEMENTS
730
731 Richard Soderberg E<lt>perl AT crystalflame DOT netE<gt> -
732 Helping me out tons, trying to find reasons for races and other weird bugs!
733
734 Simon Cozens E<lt>simon AT brecon DOT co DOT ukE<gt> -
735 Being there to answer zillions of annoying questions
736
737 Rocco Caputo E<lt>troc AT netrus DOT netE<gt>
738
739 Vipul Ved Prakash E<lt>mail AT vipul DOT netE<gt> -
740 Helping with debugging
741
742 Dean Arnold E<lt>darnold AT presicient DOT comE<gt> -
743 Stack size API
744
745 =cut