1threads(3)            User Contributed Perl Documentation           threads(3)
2
3
4

NAME

6       threads - Perl interpreter-based threads
7

VERSION

9       This document describes threads version 2.25
10

WARNING

12       The "interpreter-based threads" provided by Perl are not the fast,
13       lightweight system for multitasking that one might expect or hope for.
14       Threads are implemented in a way that makes them easy to misuse.  Few
15       people know how to use them correctly or will be able to provide help.
16
17       The use of interpreter-based threads in perl is officially discouraged.
18

SYNOPSIS

20           use threads ('yield',
21                        'stack_size' => 64*4096,
22                        'exit' => 'threads_only',
23                        'stringify');
24
25           sub start_thread {
26               my @args = @_;
27               print('Thread started: ', join(' ', @args), "\n");
28           }
29           my $thr = threads->create('start_thread', 'argument');
30           $thr->join();
31
32           threads->create(sub { print("I am a thread\n"); })->join();
33
34           my $thr2 = async { foreach (@files) { ... } };
35           $thr2->join();
36           if (my $err = $thr2->error()) {
37               warn("Thread error: $err\n");
38           }
39
40           # Invoke thread in list context (implicit) so it can return a list
41           my ($thr) = threads->create(sub { return (qw/a b c/); });
42           # or specify list context explicitly
43           my $thr = threads->create({'context' => 'list'},
44                                     sub { return (qw/a b c/); });
45           my @results = $thr->join();
46
47           $thr->detach();
48
49           # Get a thread's object
50           $thr = threads->self();
51           $thr = threads->object($tid);
52
53           # Get a thread's ID
54           $tid = threads->tid();
55           $tid = $thr->tid();
56           $tid = "$thr";
57
58           # Give other threads a chance to run
59           threads->yield();
60           yield();
61
62           # Lists of non-detached threads
63           my @threads = threads->list();
64           my $thread_count = threads->list();
65
66           my @running = threads->list(threads::running);
67           my @joinable = threads->list(threads::joinable);
68
69           # Test thread objects
70           if ($thr1 == $thr2) {
71               ...
72           }
73
74           # Manage thread stack size
75           $stack_size = threads->get_stack_size();
76           $old_size = threads->set_stack_size(32*4096);
77
78           # Create a thread with a specific context and stack size
79           my $thr = threads->create({ 'context'    => 'list',
80                                       'stack_size' => 32*4096,
81                                       'exit'       => 'thread_only' },
82                                     \&foo);
83
84           # Get thread's context
85           my $wantarray = $thr->wantarray();
86
87           # Check thread's state
88           if ($thr->is_running()) {
89               sleep(1);
90           }
91           if ($thr->is_joinable()) {
92               $thr->join();
93           }
94
95           # Send a signal to a thread
96           $thr->kill('SIGUSR1');
97
98           # Exit a thread
99           threads->exit();
100

DESCRIPTION

102       Since Perl 5.8, thread programming has been available using a model
103       called interpreter threads which provides a new Perl interpreter for
104       each thread, and, by default, results in no data or state information
105       being shared between threads.
106
107       (Prior to Perl 5.8, 5005threads was available through the "Thread.pm"
108       API.  This threading model has been deprecated, and was removed as of
109       Perl 5.10.0.)
110
111       As just mentioned, all variables are, by default, thread local.  To use
112       shared variables, you need to also load threads::shared:
113
114           use threads;
115           use threads::shared;
116
117       When loading threads::shared, you must "use threads" before you "use
118       threads::shared".  ("threads" will emit a warning if you do it the
119       other way around.)
120
121       It is strongly recommended that you enable threads via "use threads" as
122       early as possible in your script.
123
124       If needed, scripts can be written so as to run on both threaded and
125       non-threaded Perls:
126
127           my $can_use_threads = eval 'use threads; 1';
128           if ($can_use_threads) {
129               # Do processing using threads
130               ...
131           } else {
132               # Do it without using threads
133               ...
134           }
135
136       $thr = threads->create(FUNCTION, ARGS)
137           This will create a new thread that will begin execution with the
138           specified entry point function, and give it the ARGS list as
139           parameters.  It will return the corresponding threads object, or
140           "undef" if thread creation failed.
141
142           FUNCTION may either be the name of a function, an anonymous
143           subroutine, or a code ref.
144
145               my $thr = threads->create('func_name', ...);
146                   # or
147               my $thr = threads->create(sub { ... }, ...);
148                   # or
149               my $thr = threads->create(\&func, ...);
150
151           The "->new()" method is an alias for "->create()".
152
153       $thr->join()
154           This will wait for the corresponding thread to complete its
155           execution.  When the thread finishes, "->join()" will return the
156           return value(s) of the entry point function.
157
158           The context (void, scalar or list) for the return value(s) for
159           "->join()" is determined at the time of thread creation.
160
161               # Create thread in list context (implicit)
162               my ($thr1) = threads->create(sub {
163                                               my @results = qw(a b c);
164                                               return (@results);
165                                            });
166               #   or (explicit)
167               my $thr1 = threads->create({'context' => 'list'},
168                                          sub {
169                                               my @results = qw(a b c);
170                                               return (@results);
171                                          });
172               # Retrieve list results from thread
173               my @res1 = $thr1->join();
174
175               # Create thread in scalar context (implicit)
176               my $thr2 = threads->create(sub {
177                                               my $result = 42;
178                                               return ($result);
179                                            });
180               # Retrieve scalar result from thread
181               my $res2 = $thr2->join();
182
183               # Create a thread in void context (explicit)
184               my $thr3 = threads->create({'void' => 1},
185                                          sub { print("Hello, world\n"); });
186               # Join the thread in void context (i.e., no return value)
187               $thr3->join();
188
189           See "THREAD CONTEXT" for more details.
190
191           If the program exits without all threads having either been joined
192           or detached, then a warning will be issued.
193
194           Calling "->join()" or "->detach()" on an already joined thread will
195           cause an error to be thrown.
196
197       $thr->detach()
198           Makes the thread unjoinable, and causes any eventual return value
199           to be discarded.  When the program exits, any detached threads that
200           are still running are silently terminated.
201
202           If the program exits without all threads having either been joined
203           or detached, then a warning will be issued.
204
205           Calling "->join()" or "->detach()" on an already detached thread
206           will cause an error to be thrown.
207
208       threads->detach()
209           Class method that allows a thread to detach itself.
210
211       threads->self()
212           Class method that allows a thread to obtain its own threads object.
213
214       $thr->tid()
215           Returns the ID of the thread.  Thread IDs are unique integers with
216           the main thread in a program being 0, and incrementing by 1 for
217           every thread created.
218
219       threads->tid()
220           Class method that allows a thread to obtain its own ID.
221
222       "$thr"
223           If you add the "stringify" import option to your "use threads"
224           declaration, then using a threads object in a string or a string
225           context (e.g., as a hash key) will cause its ID to be used as the
226           value:
227
228               use threads qw(stringify);
229
230               my $thr = threads->create(...);
231               print("Thread $thr started\n");  # Prints: Thread 1 started
232
233       threads->object($tid)
234           This will return the threads object for the active thread
235           associated with the specified thread ID.  If $tid is the value for
236           the current thread, then this call works the same as "->self()".
237           Otherwise, returns "undef" if there is no thread associated with
238           the TID, if the thread is joined or detached, if no TID is
239           specified or if the specified TID is undef.
240
241       threads->yield()
242           This is a suggestion to the OS to let this thread yield CPU time to
243           other threads.  What actually happens is highly dependent upon the
244           underlying thread implementation.
245
246           You may do "use threads qw(yield)", and then just use "yield()" in
247           your code.
248
249       threads->list()
250       threads->list(threads::all)
251       threads->list(threads::running)
252       threads->list(threads::joinable)
253           With no arguments (or using "threads::all") and in a list context,
254           returns a list of all non-joined, non-detached threads objects.  In
255           a scalar context, returns a count of the same.
256
257           With a true argument (using "threads::running"), returns a list of
258           all non-joined, non-detached threads objects that are still
259           running.
260
261           With a false argument (using "threads::joinable"), returns a list
262           of all non-joined, non-detached threads objects that have finished
263           running (i.e., for which "->join()" will not block).
264
265       $thr1->equal($thr2)
266           Tests if two threads objects are the same thread or not.  This is
267           overloaded to the more natural forms:
268
269               if ($thr1 == $thr2) {
270                   print("Threads are the same\n");
271               }
272               # or
273               if ($thr1 != $thr2) {
274                   print("Threads differ\n");
275               }
276
277           (Thread comparison is based on thread IDs.)
278
279       async BLOCK;
280           "async" creates a thread to execute the block immediately following
281           it.  This block is treated as an anonymous subroutine, and so must
282           have a semicolon after the closing brace.  Like
283           "threads->create()", "async" returns a threads object.
284
285       $thr->error()
286           Threads are executed in an "eval" context.  This method will return
287           "undef" if the thread terminates normally.  Otherwise, it returns
288           the value of $@ associated with the thread's execution status in
289           its "eval" context.
290
291       $thr->_handle()
292           This private method returns a pointer (i.e., the memory location
293           expressed as an unsigned integer) to the internal thread structure
294           associated with a threads object.  For Win32, this is a pointer to
295           the "HANDLE" value returned by "CreateThread" (i.e., "HANDLE *");
296           for other platforms, it is a pointer to the "pthread_t" structure
297           used in the "pthread_create" call (i.e., "pthread_t *").
298
299           This method is of no use for general Perl threads programming.  Its
300           intent is to provide other (XS-based) thread modules with the
301           capability to access, and possibly manipulate, the underlying
302           thread structure associated with a Perl thread.
303
304       threads->_handle()
305           Class method that allows a thread to obtain its own handle.
306

EXITING A THREAD

308       The usual method for terminating a thread is to return() from the entry
309       point function with the appropriate return value(s).
310
311       threads->exit()
312           If needed, a thread can be exited at any time by calling
313           "threads->exit()".  This will cause the thread to return "undef" in
314           a scalar context, or the empty list in a list context.
315
316           When called from the main thread, this behaves the same as exit(0).
317
318       threads->exit(status)
319           When called from a thread, this behaves like "threads->exit()"
320           (i.e., the exit status code is ignored).
321
322           When called from the main thread, this behaves the same as
323           "exit(status)".
324
325       die()
326           Calling "die()" in a thread indicates an abnormal exit for the
327           thread.  Any $SIG{__DIE__} handler in the thread will be called
328           first, and then the thread will exit with a warning message that
329           will contain any arguments passed in the "die()" call.
330
331       exit(status)
332           Calling exit() inside a thread causes the whole application to
333           terminate.  Because of this, the use of "exit()" inside threaded
334           code, or in modules that might be used in threaded applications, is
335           strongly discouraged.
336
337           If "exit()" really is needed, then consider using the following:
338
339               threads->exit() if threads->can('exit');   # Thread friendly
340               exit(status);
341
342       use threads 'exit' => 'threads_only'
343           This globally overrides the default behavior of calling "exit()"
344           inside a thread, and effectively causes such calls to behave the
345           same as "threads->exit()".  In other words, with this setting,
346           calling "exit()" causes only the thread to terminate.
347
348           Because of its global effect, this setting should not be used
349           inside modules or the like.
350
351           The main thread is unaffected by this setting.
352
353       threads->create({'exit' => 'thread_only'}, ...)
354           This overrides the default behavior of "exit()" inside the newly
355           created thread only.
356
357       $thr->set_thread_exit_only(boolean)
358           This can be used to change the exit thread only behavior for a
359           thread after it has been created.  With a true argument, "exit()"
360           will cause only the thread to exit.  With a false argument,
361           "exit()" will terminate the application.
362
363           The main thread is unaffected by this call.
364
365       threads->set_thread_exit_only(boolean)
366           Class method for use inside a thread to change its own behavior for
367           "exit()".
368
369           The main thread is unaffected by this call.
370

THREAD STATE

372       The following boolean methods are useful in determining the state of a
373       thread.
374
375       $thr->is_running()
376           Returns true if a thread is still running (i.e., if its entry point
377           function has not yet finished or exited).
378
379       $thr->is_joinable()
380           Returns true if the thread has finished running, is not detached
381           and has not yet been joined.  In other words, the thread is ready
382           to be joined, and a call to "$thr->join()" will not block.
383
384       $thr->is_detached()
385           Returns true if the thread has been detached.
386
387       threads->is_detached()
388           Class method that allows a thread to determine whether or not it is
389           detached.
390

THREAD CONTEXT

392       As with subroutines, the type of value returned from a thread's entry
393       point function may be determined by the thread's context:  list, scalar
394       or void.  The thread's context is determined at thread creation.  This
395       is necessary so that the context is available to the entry point
396       function via wantarray().  The thread may then specify a value of the
397       appropriate type to be returned from "->join()".
398
399   Explicit context
400       Because thread creation and thread joining may occur in different
401       contexts, it may be desirable to state the context explicitly to the
402       thread's entry point function.  This may be done by calling
403       "->create()" with a hash reference as the first argument:
404
405           my $thr = threads->create({'context' => 'list'}, \&foo);
406           ...
407           my @results = $thr->join();
408
409       In the above, the threads object is returned to the parent thread in
410       scalar context, and the thread's entry point function "foo" will be
411       called in list (array) context such that the parent thread can receive
412       a list (array) from the "->join()" call.  ('array' is synonymous with
413       'list'.)
414
415       Similarly, if you need the threads object, but your thread will not be
416       returning a value (i.e., void context), you would do the following:
417
418           my $thr = threads->create({'context' => 'void'}, \&foo);
419           ...
420           $thr->join();
421
422       The context type may also be used as the key in the hash reference
423       followed by a true value:
424
425           threads->create({'scalar' => 1}, \&foo);
426           ...
427           my ($thr) = threads->list();
428           my $result = $thr->join();
429
430   Implicit context
431       If not explicitly stated, the thread's context is implied from the
432       context of the "->create()" call:
433
434           # Create thread in list context
435           my ($thr) = threads->create(...);
436
437           # Create thread in scalar context
438           my $thr = threads->create(...);
439
440           # Create thread in void context
441           threads->create(...);
442
443   $thr->wantarray()
444       This returns the thread's context in the same manner as wantarray().
445
446   threads->wantarray()
447       Class method to return the current thread's context.  This returns the
448       same value as running wantarray() inside the current thread's entry
449       point function.
450

THREAD STACK SIZE

452       The default per-thread stack size for different platforms varies
453       significantly, and is almost always far more than is needed for most
454       applications.  On Win32, Perl's makefile explicitly sets the default
455       stack to 16 MB; on most other platforms, the system default is used,
456       which again may be much larger than is needed.
457
458       By tuning the stack size to more accurately reflect your application's
459       needs, you may significantly reduce your application's memory usage,
460       and increase the number of simultaneously running threads.
461
462       Note that on Windows, address space allocation granularity is 64 KB,
463       therefore, setting the stack smaller than that on Win32 Perl will not
464       save any more memory.
465
466       threads->get_stack_size();
467           Returns the current default per-thread stack size.  The default is
468           zero, which means the system default stack size is currently in
469           use.
470
471       $size = $thr->get_stack_size();
472           Returns the stack size for a particular thread.  A return value of
473           zero indicates the system default stack size was used for the
474           thread.
475
476       $old_size = threads->set_stack_size($new_size);
477           Sets a new default per-thread stack size, and returns the previous
478           setting.
479
480           Some platforms have a minimum thread stack size.  Trying to set the
481           stack size below this value will result in a warning, and the
482           minimum stack size will be used.
483
484           Some Linux platforms have a maximum stack size.  Setting too large
485           of a stack size will cause thread creation to fail.
486
487           If needed, $new_size will be rounded up to the next multiple of the
488           memory page size (usually 4096 or 8192).
489
490           Threads created after the stack size is set will then either call
491           "pthread_attr_setstacksize()" (for pthreads platforms), or supply
492           the stack size to "CreateThread()" (for Win32 Perl).
493
494           (Obviously, this call does not affect any currently extant
495           threads.)
496
497       use threads ('stack_size' => VALUE);
498           This sets the default per-thread stack size at the start of the
499           application.
500
501       $ENV{'PERL5_ITHREADS_STACK_SIZE'}
502           The default per-thread stack size may be set at the start of the
503           application through the use of the environment variable
504           "PERL5_ITHREADS_STACK_SIZE":
505
506               PERL5_ITHREADS_STACK_SIZE=1048576
507               export PERL5_ITHREADS_STACK_SIZE
508               perl -e'use threads; print(threads->get_stack_size(), "\n")'
509
510           This value overrides any "stack_size" parameter given to "use
511           threads".  Its primary purpose is to permit setting the per-thread
512           stack size for legacy threaded applications.
513
514       threads->create({'stack_size' => VALUE}, FUNCTION, ARGS)
515           To specify a particular stack size for any individual thread, call
516           "->create()" with a hash reference as the first argument:
517
518               my $thr = threads->create({'stack_size' => 32*4096},
519                                         \&foo, @args);
520
521       $thr2 = $thr1->create(FUNCTION, ARGS)
522           This creates a new thread ($thr2) that inherits the stack size from
523           an existing thread ($thr1).  This is shorthand for the following:
524
525               my $stack_size = $thr1->get_stack_size();
526               my $thr2 = threads->create({'stack_size' => $stack_size},
527                                          FUNCTION, ARGS);
528

THREAD SIGNALLING

530       When safe signals is in effect (the default behavior - see "Unsafe
531       signals" for more details), then signals may be sent and acted upon by
532       individual threads.
533
534       $thr->kill('SIG...');
535           Sends the specified signal to the thread.  Signal names and
536           (positive) signal numbers are the same as those supported by
537           kill().  For example, 'SIGTERM', 'TERM' and (depending on the OS)
538           15 are all valid arguments to "->kill()".
539
540           Returns the thread object to allow for method chaining:
541
542               $thr->kill('SIG...')->join();
543
544       Signal handlers need to be set up in the threads for the signals they
545       are expected to act upon.  Here's an example for cancelling a thread:
546
547           use threads;
548
549           sub thr_func
550           {
551               # Thread 'cancellation' signal handler
552               $SIG{'KILL'} = sub { threads->exit(); };
553
554               ...
555           }
556
557           # Create a thread
558           my $thr = threads->create('thr_func');
559
560           ...
561
562           # Signal the thread to terminate, and then detach
563           # it so that it will get cleaned up automatically
564           $thr->kill('KILL')->detach();
565
566       Here's another simplistic example that illustrates the use of thread
567       signalling in conjunction with a semaphore to provide rudimentary
568       suspend and resume capabilities:
569
570           use threads;
571           use Thread::Semaphore;
572
573           sub thr_func
574           {
575               my $sema = shift;
576
577               # Thread 'suspend/resume' signal handler
578               $SIG{'STOP'} = sub {
579                   $sema->down();      # Thread suspended
580                   $sema->up();        # Thread resumes
581               };
582
583               ...
584           }
585
586           # Create a semaphore and pass it to a thread
587           my $sema = Thread::Semaphore->new();
588           my $thr = threads->create('thr_func', $sema);
589
590           # Suspend the thread
591           $sema->down();
592           $thr->kill('STOP');
593
594           ...
595
596           # Allow the thread to continue
597           $sema->up();
598
599       CAVEAT:  The thread signalling capability provided by this module does
600       not actually send signals via the OS.  It emulates signals at the Perl-
601       level such that signal handlers are called in the appropriate thread.
602       For example, sending "$thr->kill('STOP')" does not actually suspend a
603       thread (or the whole process), but does cause a $SIG{'STOP'} handler to
604       be called in that thread (as illustrated above).
605
606       As such, signals that would normally not be appropriate to use in the
607       "kill()" command (e.g., "kill('KILL', $$)") are okay to use with the
608       "->kill()" method (again, as illustrated above).
609
610       Correspondingly, sending a signal to a thread does not disrupt the
611       operation the thread is currently working on:  The signal will be acted
612       upon after the current operation has completed.  For instance, if the
613       thread is stuck on an I/O call, sending it a signal will not cause the
614       I/O call to be interrupted such that the signal is acted up
615       immediately.
616
617       Sending a signal to a terminated/finished thread is ignored.
618

WARNINGS

620       Perl exited with active threads:
621           If the program exits without all threads having either been joined
622           or detached, then this warning will be issued.
623
624           NOTE:  If the main thread exits, then this warning cannot be
625           suppressed using "no warnings 'threads';" as suggested below.
626
627       Thread creation failed: pthread_create returned #
628           See the appropriate man page for "pthread_create" to determine the
629           actual cause for the failure.
630
631       Thread # terminated abnormally: ...
632           A thread terminated in some manner other than just returning from
633           its entry point function, or by using "threads->exit()".  For
634           example, the thread may have terminated because of an error, or by
635           using "die".
636
637       Using minimum thread stack size of #
638           Some platforms have a minimum thread stack size.  Trying to set the
639           stack size below this value will result in the above warning, and
640           the stack size will be set to the minimum.
641
642       Thread creation failed: pthread_attr_setstacksize(SIZE) returned 22
643           The specified SIZE exceeds the system's maximum stack size.  Use a
644           smaller value for the stack size.
645
646       If needed, thread warnings can be suppressed by using:
647
648           no warnings 'threads';
649
650       in the appropriate scope.
651

ERRORS

653       This Perl not built to support threads
654           The particular copy of Perl that you're trying to use was not built
655           using the "useithreads" configuration option.
656
657           Having threads support requires all of Perl and all of the XS
658           modules in the Perl installation to be rebuilt; it is not just a
659           question of adding the threads module (i.e., threaded and non-
660           threaded Perls are binary incompatible).
661
662       Cannot change stack size of an existing thread
663           The stack size of currently extant threads cannot be changed,
664           therefore, the following results in the above error:
665
666               $thr->set_stack_size($size);
667
668       Cannot signal threads without safe signals
669           Safe signals must be in effect to use the "->kill()" signalling
670           method.  See "Unsafe signals" for more details.
671
672       Unrecognized signal name: ...
673           The particular copy of Perl that you're trying to use does not
674           support the specified signal being used in a "->kill()" call.
675

BUGS AND LIMITATIONS

677       Before you consider posting a bug report, please consult, and possibly
678       post a message to the discussion forum to see if what you've
679       encountered is a known problem.
680
681       Thread-safe modules
682           See "Making your module threadsafe" in perlmod when creating
683           modules that may be used in threaded applications, especially if
684           those modules use non-Perl data, or XS code.
685
686       Using non-thread-safe modules
687           Unfortunately, you may encounter Perl modules that are not thread-
688           safe.  For example, they may crash the Perl interpreter during
689           execution, or may dump core on termination.  Depending on the
690           module and the requirements of your application, it may be possible
691           to work around such difficulties.
692
693           If the module will only be used inside a thread, you can try
694           loading the module from inside the thread entry point function
695           using "require" (and "import" if needed):
696
697               sub thr_func
698               {
699                   require Unsafe::Module
700                   # Unsafe::Module->import(...);
701
702                   ....
703               }
704
705           If the module is needed inside the main thread, try modifying your
706           application so that the module is loaded (again using "require" and
707           "->import()") after any threads are started, and in such a way that
708           no other threads are started afterwards.
709
710           If the above does not work, or is not adequate for your
711           application, then file a bug report on
712           <https://rt.cpan.org/Public/> against the problematic module.
713
714       Memory consumption
715           On most systems, frequent and continual creation and destruction of
716           threads can lead to ever-increasing growth in the memory footprint
717           of the Perl interpreter.  While it is simple to just launch threads
718           and then "->join()" or "->detach()" them, for long-lived
719           applications, it is better to maintain a pool of threads, and to
720           reuse them for the work needed, using queues to notify threads of
721           pending work.  The CPAN distribution of this module contains a
722           simple example (examples/pool_reuse.pl) illustrating the creation,
723           use and monitoring of a pool of reusable threads.
724
725       Current working directory
726           On all platforms except MSWin32, the setting for the current
727           working directory is shared among all threads such that changing it
728           in one thread (e.g., using "chdir()") will affect all the threads
729           in the application.
730
731           On MSWin32, each thread maintains its own the current working
732           directory setting.
733
734       Locales
735           Prior to Perl 5.28, locales could not be used with threads, due to
736           various race conditions.  Starting in that release, on systems that
737           implement thread-safe locale functions, threads can be used, with
738           some caveats.  This includes Windows starting with Visual Studio
739           2005, and systems compatible with POSIX 2008.  See "Multi-threaded
740           operation" in perllocale.
741
742           Each thread (except the main thread) is started using the C locale.
743           The main thread is started like all other Perl programs; see
744           "ENVIRONMENT" in perllocale.  You can switch locales in any thread
745           as often as you like.
746
747           If you want to inherit the parent thread's locale, you can, in the
748           parent, set a variable like so:
749
750               $foo = POSIX::setlocale(LC_ALL, NULL);
751
752           and then pass to threads->create() a sub that closes over $foo.
753           Then, in the child, you say
754
755               POSIX::setlocale(LC_ALL, $foo);
756
757           Or you can use the facilities in threads::shared to pass $foo; or
758           if the environment hasn't changed, in the child, do
759
760               POSIX::setlocale(LC_ALL, "");
761
762       Environment variables
763           Currently, on all platforms except MSWin32, all system calls (e.g.,
764           using "system()" or back-ticks) made from threads use the
765           environment variable settings from the main thread.  In other
766           words, changes made to %ENV in a thread will not be visible in
767           system calls made by that thread.
768
769           To work around this, set environment variables as part of the
770           system call.  For example:
771
772               my $msg = 'hello';
773               system("FOO=$msg; echo \$FOO");   # Outputs 'hello' to STDOUT
774
775           On MSWin32, each thread maintains its own set of environment
776           variables.
777
778       Catching signals
779           Signals are caught by the main thread (thread ID = 0) of a script.
780           Therefore, setting up signal handlers in threads for purposes other
781           than "THREAD SIGNALLING" as documented above will not accomplish
782           what is intended.
783
784           This is especially true if trying to catch "SIGALRM" in a thread.
785           To handle alarms in threads, set up a signal handler in the main
786           thread, and then use "THREAD SIGNALLING" to relay the signal to the
787           thread:
788
789             # Create thread with a task that may time out
790             my $thr = threads->create(sub {
791                 threads->yield();
792                 eval {
793                     $SIG{ALRM} = sub { die("Timeout\n"); };
794                     alarm(10);
795                     ...  # Do work here
796                     alarm(0);
797                 };
798                 if ($@ =~ /Timeout/) {
799                     warn("Task in thread timed out\n");
800                 }
801             };
802
803             # Set signal handler to relay SIGALRM to thread
804             $SIG{ALRM} = sub { $thr->kill('ALRM') };
805
806             ... # Main thread continues working
807
808       Parent-child threads
809           On some platforms, it might not be possible to destroy parent
810           threads while there are still existing child threads.
811
812       Unsafe signals
813           Since Perl 5.8.0, signals have been made safer in Perl by
814           postponing their handling until the interpreter is in a safe state.
815           See "Safe Signals" in perl58delta and "Deferred Signals (Safe
816           Signals)" in perlipc for more details.
817
818           Safe signals is the default behavior, and the old, immediate,
819           unsafe signalling behavior is only in effect in the following
820           situations:
821
822           •   Perl has been built with "PERL_OLD_SIGNALS" (see "perl -V").
823
824           •   The environment variable "PERL_SIGNALS" is set to "unsafe" (see
825               "PERL_SIGNALS" in perlrun).
826
827           •   The module Perl::Unsafe::Signals is used.
828
829           If unsafe signals is in effect, then signal handling is not thread-
830           safe, and the "->kill()" signalling method cannot be used.
831
832       Identity of objects returned from threads
833           When a value is returned from a thread through a "join" operation,
834           the value and everything that it references is copied across to the
835           joining thread, in much the same way that values are copied upon
836           thread creation.  This works fine for most kinds of value,
837           including arrays, hashes, and subroutines.  The copying recurses
838           through array elements, reference scalars, variables closed over by
839           subroutines, and other kinds of reference.
840
841           However, everything referenced by the returned value is a fresh
842           copy in the joining thread, even if a returned object had in the
843           child thread been a copy of something that previously existed in
844           the parent thread.  After joining, the parent will therefore have a
845           duplicate of each such object.  This sometimes matters, especially
846           if the object gets mutated; this can especially matter for private
847           data to which a returned subroutine provides access.
848
849       Returning blessed objects from threads
850           Returning blessed objects from threads does not work.  Depending on
851           the classes involved, you may be able to work around this by
852           returning a serialized version of the object (e.g., using
853           Data::Dumper or Storable), and then reconstituting it in the
854           joining thread.  If you're using Perl 5.10.0 or later, and if the
855           class supports shared objects, you can pass them via shared queues.
856
857       END blocks in threads
858           It is possible to add END blocks to threads by using require or
859           eval with the appropriate code.  These "END" blocks will then be
860           executed when the thread's interpreter is destroyed (i.e., either
861           during a "->join()" call, or at program termination).
862
863           However, calling any threads methods in such an "END" block will
864           most likely fail (e.g., the application may hang, or generate an
865           error) due to mutexes that are needed to control functionality
866           within the threads module.
867
868           For this reason, the use of "END" blocks in threads is strongly
869           discouraged.
870
871       Open directory handles
872           In perl 5.14 and higher, on systems other than Windows that do not
873           support the "fchdir" C function, directory handles (see opendir)
874           will not be copied to new threads. You can use the "d_fchdir"
875           variable in Config.pm to determine whether your system supports it.
876
877           In prior perl versions, spawning threads with open directory
878           handles would crash the interpreter.  [perl #75154]
879           <https://rt.perl.org/rt3/Public/Bug/Display.html?id=75154>
880
881       Detached threads and global destruction
882           If the main thread exits while there are detached threads which are
883           still running, then Perl's global destruction phase is not executed
884           because otherwise certain global structures that control the
885           operation of threads and that are allocated in the main thread's
886           memory may get destroyed before the detached thread is destroyed.
887
888           If you are using any code that requires the execution of the global
889           destruction phase for clean up (e.g., removing temp files), then do
890           not use detached threads, but rather join all threads before
891           exiting the program.
892
893       Perl Bugs and the CPAN Version of threads
894           Support for threads extends beyond the code in this module (i.e.,
895           threads.pm and threads.xs), and into the Perl interpreter itself.
896           Older versions of Perl contain bugs that may manifest themselves
897           despite using the latest version of threads from CPAN.  There is no
898           workaround for this other than upgrading to the latest version of
899           Perl.
900
901           Even with the latest version of Perl, it is known that certain
902           constructs with threads may result in warning messages concerning
903           leaked scalars or unreferenced scalars.  However, such warnings are
904           harmless, and may safely be ignored.
905
906           You can search for threads related bug reports at
907           <https://rt.cpan.org/Public/>.  If needed submit any new bugs,
908           problems, patches, etc. to:
909           <https://rt.cpan.org/Public/Dist/Display.html?Name=threads>
910

REQUIREMENTS

912       Perl 5.8.0 or later
913

SEE ALSO

915       threads on MetaCPAN: <https://metacpan.org/release/threads>
916
917       Code repository for CPAN distribution:
918       <https://github.com/Dual-Life/threads>
919
920       threads::shared, perlthrtut
921
922       <https://www.perl.com/pub/a/2002/06/11/threads.html> and
923       <https://www.perl.com/pub/a/2002/09/04/threads.html>
924
925       Perl threads mailing list: <https://lists.perl.org/list/ithreads.html>
926
927       Stack size discussion: <https://www.perlmonks.org/?node_id=532956>
928
929       Sample code in the examples directory of this distribution on CPAN.
930

AUTHOR

932       Artur Bergman <sky AT crucially DOT net>
933
934       CPAN version produced by Jerry D. Hedden <jdhedden AT cpan DOT org>
935

LICENSE

937       threads is released under the same license as Perl.
938

ACKNOWLEDGEMENTS

940       Richard Soderberg <perl AT crystalflame DOT net> - Helping me out tons,
941       trying to find reasons for races and other weird bugs!
942
943       Simon Cozens <simon AT brecon DOT co DOT uk> - Being there to answer
944       zillions of annoying questions
945
946       Rocco Caputo <troc AT netrus DOT net>
947
948       Vipul Ved Prakash <mail AT vipul DOT net> - Helping with debugging
949
950       Dean Arnold <darnold AT presicient DOT com> - Stack size API
951
952
953
954perl v5.32.1                      2021-01-27                        threads(3)
Impressum