xref: /openbsd-src/gnu/usr.bin/perl/dist/threads/lib/threads.pm (revision 3d61058aa5c692477b6d18acfbbdb653a9930ff9)
1898184e3Ssthenpackage threads;
2898184e3Ssthen
3898184e3Ssthenuse 5.008;
4898184e3Ssthen
5898184e3Ssthenuse strict;
6898184e3Ssthenuse warnings;
7898184e3Ssthen
8*3d61058aSafresh1our $VERSION = '2.40';      # remember to update version in POD!
9898184e3Ssthenmy $XS_VERSION = $VERSION;
10*3d61058aSafresh1#$VERSION = eval $VERSION;
11898184e3Ssthen
12898184e3Ssthen# Verify this Perl supports threads
13898184e3Ssthenrequire Config;
14898184e3Ssthenif (! $Config::Config{useithreads}) {
15898184e3Ssthen    die("This Perl not built to support threads\n");
16898184e3Ssthen}
17898184e3Ssthen
18898184e3Ssthen# Complain if 'threads' is loaded after 'threads::shared'
19898184e3Ssthenif ($threads::shared::threads_shared) {
20898184e3Ssthen    warn <<'_MSG_';
21898184e3SsthenWarning, threads::shared has already been loaded.  To
22898184e3Ssthenenable shared variables, 'use threads' must be called
23898184e3Ssthenbefore threads::shared or any module that uses it.
24898184e3Ssthen_MSG_
25898184e3Ssthen}
26898184e3Ssthen
27898184e3Ssthen# Declare that we have been loaded
28898184e3Ssthen$threads::threads = 1;
29898184e3Ssthen
30898184e3Ssthen# Load the XS code
31898184e3Ssthenrequire XSLoader;
32898184e3SsthenXSLoader::load('threads', $XS_VERSION);
33898184e3Ssthen
34898184e3Ssthen
35898184e3Ssthen### Export ###
36898184e3Ssthen
37898184e3Ssthensub import
38898184e3Ssthen{
39898184e3Ssthen    my $class = shift;   # Not used
40898184e3Ssthen
41898184e3Ssthen    # Exported subroutines
42898184e3Ssthen    my @EXPORT = qw(async);
43898184e3Ssthen
44898184e3Ssthen    # Handle args
45898184e3Ssthen    while (my $sym = shift) {
46898184e3Ssthen        if ($sym =~ /^(?:stack|exit)/i) {
47898184e3Ssthen            if (defined(my $arg = shift)) {
48898184e3Ssthen                if ($sym =~ /^stack/i) {
49898184e3Ssthen                    threads->set_stack_size($arg);
50898184e3Ssthen                } else {
51898184e3Ssthen                    $threads::thread_exit_only = $arg =~ /^thread/i;
52898184e3Ssthen                }
53898184e3Ssthen            } else {
54898184e3Ssthen                require Carp;
55898184e3Ssthen                Carp::croak("threads: Missing argument for option: $sym");
56898184e3Ssthen            }
57898184e3Ssthen
58898184e3Ssthen        } elsif ($sym =~ /^str/i) {
59898184e3Ssthen            import overload ('""' => \&tid);
60898184e3Ssthen
61898184e3Ssthen        } elsif ($sym =~ /^(?::all|yield)$/) {
62898184e3Ssthen            push(@EXPORT, qw(yield));
63898184e3Ssthen
64898184e3Ssthen        } else {
65898184e3Ssthen            require Carp;
66898184e3Ssthen            Carp::croak("threads: Unknown import option: $sym");
67898184e3Ssthen        }
68898184e3Ssthen    }
69898184e3Ssthen
70898184e3Ssthen    # Export subroutine names
71898184e3Ssthen    my $caller = caller();
72898184e3Ssthen    foreach my $sym (@EXPORT) {
73898184e3Ssthen        no strict 'refs';
74898184e3Ssthen        *{$caller.'::'.$sym} = \&{$sym};
75898184e3Ssthen    }
76898184e3Ssthen
77898184e3Ssthen    # Set stack size via environment variable
78898184e3Ssthen    if (exists($ENV{'PERL5_ITHREADS_STACK_SIZE'})) {
79898184e3Ssthen        threads->set_stack_size($ENV{'PERL5_ITHREADS_STACK_SIZE'});
80898184e3Ssthen    }
81898184e3Ssthen}
82898184e3Ssthen
83898184e3Ssthen
84898184e3Ssthen### Methods, etc. ###
85898184e3Ssthen
86898184e3Ssthen# Exit from a thread (only)
87898184e3Ssthensub exit
88898184e3Ssthen{
89898184e3Ssthen    my ($class, $status) = @_;
90898184e3Ssthen    if (! defined($status)) {
91898184e3Ssthen        $status = 0;
92898184e3Ssthen    }
93898184e3Ssthen
94898184e3Ssthen    # Class method only
95898184e3Ssthen    if (ref($class)) {
96898184e3Ssthen        require Carp;
97898184e3Ssthen        Carp::croak('Usage: threads->exit(status)');
98898184e3Ssthen    }
99898184e3Ssthen
100898184e3Ssthen    $class->set_thread_exit_only(1);
101898184e3Ssthen    CORE::exit($status);
102898184e3Ssthen}
103898184e3Ssthen
104898184e3Ssthen# 'Constant' args for threads->list()
105898184e3Ssthensub threads::all      { }
106898184e3Ssthensub threads::running  { 1 }
107898184e3Ssthensub threads::joinable { 0 }
108898184e3Ssthen
109898184e3Ssthen# 'new' is an alias for 'create'
110898184e3Ssthen*new = \&create;
111898184e3Ssthen
112898184e3Ssthen# 'async' is a function alias for the 'threads->create()' method
113898184e3Ssthensub async (&;@)
114898184e3Ssthen{
115898184e3Ssthen    unshift(@_, 'threads');
116898184e3Ssthen    # Use "goto" trick to avoid pad problems from 5.8.1 (fixed in 5.8.2)
117898184e3Ssthen    goto &create;
118898184e3Ssthen}
119898184e3Ssthen
120898184e3Ssthen# Thread object equality checking
121898184e3Ssthenuse overload (
122898184e3Ssthen    '==' => \&equal,
123898184e3Ssthen    '!=' => sub { ! equal(@_) },
124898184e3Ssthen    'fallback' => 1
125898184e3Ssthen);
126898184e3Ssthen
127898184e3Ssthen1;
128898184e3Ssthen
129898184e3Ssthen__END__
130898184e3Ssthen
131898184e3Ssthen=head1 NAME
132898184e3Ssthen
133898184e3Ssthenthreads - Perl interpreter-based threads
134898184e3Ssthen
135898184e3Ssthen=head1 VERSION
136898184e3Ssthen
137*3d61058aSafresh1This document describes threads version 2.40
1386fb12b70Safresh1
1396fb12b70Safresh1=head1 WARNING
1406fb12b70Safresh1
1416fb12b70Safresh1The "interpreter-based threads" provided by Perl are not the fast, lightweight
1426fb12b70Safresh1system for multitasking that one might expect or hope for.  Threads are
14356d68f1eSafresh1implemented in a way that makes them easy to misuse.  Few people know how to
1446fb12b70Safresh1use them correctly or will be able to provide help.
1456fb12b70Safresh1
1466fb12b70Safresh1The use of interpreter-based threads in perl is officially
1476fb12b70Safresh1L<discouraged|perlpolicy/discouraged>.
148898184e3Ssthen
149898184e3Ssthen=head1 SYNOPSIS
150898184e3Ssthen
151898184e3Ssthen    use threads ('yield',
152898184e3Ssthen                 'stack_size' => 64*4096,
153898184e3Ssthen                 'exit' => 'threads_only',
154898184e3Ssthen                 'stringify');
155898184e3Ssthen
156898184e3Ssthen    sub start_thread {
157898184e3Ssthen        my @args = @_;
158898184e3Ssthen        print('Thread started: ', join(' ', @args), "\n");
159898184e3Ssthen    }
160898184e3Ssthen    my $thr = threads->create('start_thread', 'argument');
161898184e3Ssthen    $thr->join();
162898184e3Ssthen
163898184e3Ssthen    threads->create(sub { print("I am a thread\n"); })->join();
164898184e3Ssthen
165898184e3Ssthen    my $thr2 = async { foreach (@files) { ... } };
166898184e3Ssthen    $thr2->join();
167898184e3Ssthen    if (my $err = $thr2->error()) {
168898184e3Ssthen        warn("Thread error: $err\n");
169898184e3Ssthen    }
170898184e3Ssthen
171898184e3Ssthen    # Invoke thread in list context (implicit) so it can return a list
172898184e3Ssthen    my ($thr) = threads->create(sub { return (qw/a b c/); });
173898184e3Ssthen    # or specify list context explicitly
174898184e3Ssthen    my $thr = threads->create({'context' => 'list'},
175898184e3Ssthen                              sub { return (qw/a b c/); });
176898184e3Ssthen    my @results = $thr->join();
177898184e3Ssthen
178898184e3Ssthen    $thr->detach();
179898184e3Ssthen
180898184e3Ssthen    # Get a thread's object
181898184e3Ssthen    $thr = threads->self();
182898184e3Ssthen    $thr = threads->object($tid);
183898184e3Ssthen
184898184e3Ssthen    # Get a thread's ID
185898184e3Ssthen    $tid = threads->tid();
186898184e3Ssthen    $tid = $thr->tid();
187898184e3Ssthen    $tid = "$thr";
188898184e3Ssthen
189898184e3Ssthen    # Give other threads a chance to run
190898184e3Ssthen    threads->yield();
191898184e3Ssthen    yield();
192898184e3Ssthen
193898184e3Ssthen    # Lists of non-detached threads
194898184e3Ssthen    my @threads = threads->list();
195898184e3Ssthen    my $thread_count = threads->list();
196898184e3Ssthen
197898184e3Ssthen    my @running = threads->list(threads::running);
198898184e3Ssthen    my @joinable = threads->list(threads::joinable);
199898184e3Ssthen
200898184e3Ssthen    # Test thread objects
201898184e3Ssthen    if ($thr1 == $thr2) {
202898184e3Ssthen        ...
203898184e3Ssthen    }
204898184e3Ssthen
205898184e3Ssthen    # Manage thread stack size
206898184e3Ssthen    $stack_size = threads->get_stack_size();
207898184e3Ssthen    $old_size = threads->set_stack_size(32*4096);
208898184e3Ssthen
209898184e3Ssthen    # Create a thread with a specific context and stack size
210898184e3Ssthen    my $thr = threads->create({ 'context'    => 'list',
211898184e3Ssthen                                'stack_size' => 32*4096,
212898184e3Ssthen                                'exit'       => 'thread_only' },
213898184e3Ssthen                              \&foo);
214898184e3Ssthen
215898184e3Ssthen    # Get thread's context
216898184e3Ssthen    my $wantarray = $thr->wantarray();
217898184e3Ssthen
218898184e3Ssthen    # Check thread's state
219898184e3Ssthen    if ($thr->is_running()) {
220898184e3Ssthen        sleep(1);
221898184e3Ssthen    }
222898184e3Ssthen    if ($thr->is_joinable()) {
223898184e3Ssthen        $thr->join();
224898184e3Ssthen    }
225898184e3Ssthen
226898184e3Ssthen    # Send a signal to a thread
227898184e3Ssthen    $thr->kill('SIGUSR1');
228898184e3Ssthen
229898184e3Ssthen    # Exit a thread
230898184e3Ssthen    threads->exit();
231898184e3Ssthen
232898184e3Ssthen=head1 DESCRIPTION
233898184e3Ssthen
234898184e3SsthenSince Perl 5.8, thread programming has been available using a model called
235898184e3SsthenI<interpreter threads> which provides a new Perl interpreter for each
236898184e3Ssthenthread, and, by default, results in no data or state information being shared
237898184e3Ssthenbetween threads.
238898184e3Ssthen
239898184e3Ssthen(Prior to Perl 5.8, I<5005threads> was available through the C<Thread.pm> API.
240898184e3SsthenThis threading model has been deprecated, and was removed as of Perl 5.10.0.)
241898184e3Ssthen
242898184e3SsthenAs just mentioned, all variables are, by default, thread local.  To use shared
243898184e3Ssthenvariables, you need to also load L<threads::shared>:
244898184e3Ssthen
245898184e3Ssthen    use threads;
246898184e3Ssthen    use threads::shared;
247898184e3Ssthen
248898184e3SsthenWhen loading L<threads::shared>, you must C<use threads> before you
249898184e3SsthenC<use threads::shared>.  (C<threads> will emit a warning if you do it the
250898184e3Ssthenother way around.)
251898184e3Ssthen
252898184e3SsthenIt is strongly recommended that you enable threads via C<use threads> as early
253898184e3Ssthenas possible in your script.
254898184e3Ssthen
255898184e3SsthenIf needed, scripts can be written so as to run on both threaded and
256898184e3Ssthennon-threaded Perls:
257898184e3Ssthen
258898184e3Ssthen    my $can_use_threads = eval 'use threads; 1';
259898184e3Ssthen    if ($can_use_threads) {
260898184e3Ssthen        # Do processing using threads
261898184e3Ssthen        ...
262898184e3Ssthen    } else {
263898184e3Ssthen        # Do it without using threads
264898184e3Ssthen        ...
265898184e3Ssthen    }
266898184e3Ssthen
267898184e3Ssthen=over
268898184e3Ssthen
269898184e3Ssthen=item $thr = threads->create(FUNCTION, ARGS)
270898184e3Ssthen
271898184e3SsthenThis will create a new thread that will begin execution with the specified
272898184e3Ssthenentry point function, and give it the I<ARGS> list as parameters.  It will
273898184e3Ssthenreturn the corresponding threads object, or C<undef> if thread creation failed.
274898184e3Ssthen
275898184e3SsthenI<FUNCTION> may either be the name of a function, an anonymous subroutine, or
276898184e3Ssthena code ref.
277898184e3Ssthen
278898184e3Ssthen    my $thr = threads->create('func_name', ...);
279898184e3Ssthen        # or
280898184e3Ssthen    my $thr = threads->create(sub { ... }, ...);
281898184e3Ssthen        # or
282898184e3Ssthen    my $thr = threads->create(\&func, ...);
283898184e3Ssthen
284898184e3SsthenThe C<-E<gt>new()> method is an alias for C<-E<gt>create()>.
285898184e3Ssthen
286898184e3Ssthen=item $thr->join()
287898184e3Ssthen
288898184e3SsthenThis will wait for the corresponding thread to complete its execution.  When
289898184e3Ssthenthe thread finishes, C<-E<gt>join()> will return the return value(s) of the
290898184e3Ssthenentry point function.
291898184e3Ssthen
292898184e3SsthenThe context (void, scalar or list) for the return value(s) for C<-E<gt>join()>
293898184e3Ssthenis determined at the time of thread creation.
294898184e3Ssthen
295898184e3Ssthen    # Create thread in list context (implicit)
296898184e3Ssthen    my ($thr1) = threads->create(sub {
297898184e3Ssthen                                    my @results = qw(a b c);
298898184e3Ssthen                                    return (@results);
299898184e3Ssthen                                 });
300898184e3Ssthen    #   or (explicit)
301898184e3Ssthen    my $thr1 = threads->create({'context' => 'list'},
302898184e3Ssthen                               sub {
303898184e3Ssthen                                    my @results = qw(a b c);
304898184e3Ssthen                                    return (@results);
305898184e3Ssthen                               });
306898184e3Ssthen    # Retrieve list results from thread
307898184e3Ssthen    my @res1 = $thr1->join();
308898184e3Ssthen
309898184e3Ssthen    # Create thread in scalar context (implicit)
310898184e3Ssthen    my $thr2 = threads->create(sub {
311898184e3Ssthen                                    my $result = 42;
312898184e3Ssthen                                    return ($result);
313898184e3Ssthen                                 });
314898184e3Ssthen    # Retrieve scalar result from thread
315898184e3Ssthen    my $res2 = $thr2->join();
316898184e3Ssthen
317898184e3Ssthen    # Create a thread in void context (explicit)
318898184e3Ssthen    my $thr3 = threads->create({'void' => 1},
319898184e3Ssthen                               sub { print("Hello, world\n"); });
320898184e3Ssthen    # Join the thread in void context (i.e., no return value)
321898184e3Ssthen    $thr3->join();
322898184e3Ssthen
323898184e3SsthenSee L</"THREAD CONTEXT"> for more details.
324898184e3Ssthen
325898184e3SsthenIf the program exits without all threads having either been joined or
326898184e3Ssthendetached, then a warning will be issued.
327898184e3Ssthen
328898184e3SsthenCalling C<-E<gt>join()> or C<-E<gt>detach()> on an already joined thread will
329898184e3Ssthencause an error to be thrown.
330898184e3Ssthen
331898184e3Ssthen=item $thr->detach()
332898184e3Ssthen
333898184e3SsthenMakes the thread unjoinable, and causes any eventual return value to be
334898184e3Ssthendiscarded.  When the program exits, any detached threads that are still
335898184e3Ssthenrunning are silently terminated.
336898184e3Ssthen
337898184e3SsthenIf the program exits without all threads having either been joined or
338898184e3Ssthendetached, then a warning will be issued.
339898184e3Ssthen
340898184e3SsthenCalling C<-E<gt>join()> or C<-E<gt>detach()> on an already detached thread
341898184e3Ssthenwill cause an error to be thrown.
342898184e3Ssthen
343898184e3Ssthen=item threads->detach()
344898184e3Ssthen
345898184e3SsthenClass method that allows a thread to detach itself.
346898184e3Ssthen
347898184e3Ssthen=item threads->self()
348898184e3Ssthen
349898184e3SsthenClass method that allows a thread to obtain its own I<threads> object.
350898184e3Ssthen
351898184e3Ssthen=item $thr->tid()
352898184e3Ssthen
353898184e3SsthenReturns the ID of the thread.  Thread IDs are unique integers with the main
354898184e3Ssthenthread in a program being 0, and incrementing by 1 for every thread created.
355898184e3Ssthen
356898184e3Ssthen=item threads->tid()
357898184e3Ssthen
358898184e3SsthenClass method that allows a thread to obtain its own ID.
359898184e3Ssthen
360898184e3Ssthen=item "$thr"
361898184e3Ssthen
362898184e3SsthenIf you add the C<stringify> import option to your C<use threads> declaration,
363898184e3Ssthenthen using a threads object in a string or a string context (e.g., as a hash
364898184e3Ssthenkey) will cause its ID to be used as the value:
365898184e3Ssthen
366898184e3Ssthen    use threads qw(stringify);
367898184e3Ssthen
368898184e3Ssthen    my $thr = threads->create(...);
369b8851fccSafresh1    print("Thread $thr started\n");  # Prints: Thread 1 started
370898184e3Ssthen
371898184e3Ssthen=item threads->object($tid)
372898184e3Ssthen
373898184e3SsthenThis will return the I<threads> object for the I<active> thread associated
374898184e3Ssthenwith the specified thread ID.  If C<$tid> is the value for the current thread,
375898184e3Ssthenthen this call works the same as C<-E<gt>self()>.  Otherwise, returns C<undef>
376898184e3Ssthenif there is no thread associated with the TID, if the thread is joined or
377898184e3Ssthendetached, if no TID is specified or if the specified TID is undef.
378898184e3Ssthen
379898184e3Ssthen=item threads->yield()
380898184e3Ssthen
381898184e3SsthenThis is a suggestion to the OS to let this thread yield CPU time to other
382898184e3Ssthenthreads.  What actually happens is highly dependent upon the underlying
383898184e3Ssthenthread implementation.
384898184e3Ssthen
385898184e3SsthenYou may do C<use threads qw(yield)>, and then just use C<yield()> in your
386898184e3Ssthencode.
387898184e3Ssthen
388898184e3Ssthen=item threads->list()
389898184e3Ssthen
390898184e3Ssthen=item threads->list(threads::all)
391898184e3Ssthen
392898184e3Ssthen=item threads->list(threads::running)
393898184e3Ssthen
394898184e3Ssthen=item threads->list(threads::joinable)
395898184e3Ssthen
396898184e3SsthenWith no arguments (or using C<threads::all>) and in a list context, returns a
397898184e3Ssthenlist of all non-joined, non-detached I<threads> objects.  In a scalar context,
398898184e3Ssthenreturns a count of the same.
399898184e3Ssthen
400898184e3SsthenWith a I<true> argument (using C<threads::running>), returns a list of all
401898184e3Ssthennon-joined, non-detached I<threads> objects that are still running.
402898184e3Ssthen
403898184e3SsthenWith a I<false> argument (using C<threads::joinable>), returns a list of all
404898184e3Ssthennon-joined, non-detached I<threads> objects that have finished running (i.e.,
405898184e3Ssthenfor which C<-E<gt>join()> will not I<block>).
406898184e3Ssthen
407898184e3Ssthen=item $thr1->equal($thr2)
408898184e3Ssthen
409898184e3SsthenTests if two threads objects are the same thread or not.  This is overloaded
410898184e3Ssthento the more natural forms:
411898184e3Ssthen
412898184e3Ssthen    if ($thr1 == $thr2) {
413898184e3Ssthen        print("Threads are the same\n");
414898184e3Ssthen    }
415898184e3Ssthen    # or
416898184e3Ssthen    if ($thr1 != $thr2) {
417898184e3Ssthen        print("Threads differ\n");
418898184e3Ssthen    }
419898184e3Ssthen
420898184e3Ssthen(Thread comparison is based on thread IDs.)
421898184e3Ssthen
422898184e3Ssthen=item async BLOCK;
423898184e3Ssthen
424898184e3SsthenC<async> creates a thread to execute the block immediately following
425898184e3Ssthenit.  This block is treated as an anonymous subroutine, and so must have a
426898184e3Ssthensemicolon after the closing brace.  Like C<threads-E<gt>create()>, C<async>
427898184e3Ssthenreturns a I<threads> object.
428898184e3Ssthen
429898184e3Ssthen=item $thr->error()
430898184e3Ssthen
431898184e3SsthenThreads are executed in an C<eval> context.  This method will return C<undef>
432898184e3Ssthenif the thread terminates I<normally>.  Otherwise, it returns the value of
433898184e3SsthenC<$@> associated with the thread's execution status in its C<eval> context.
434898184e3Ssthen
435898184e3Ssthen=item $thr->_handle()
436898184e3Ssthen
4376fb12b70Safresh1This I<private> method returns a pointer (i.e., the memory location expressed
4386fb12b70Safresh1as an unsigned integer) to the internal thread structure associated with a
4396fb12b70Safresh1threads object.  For Win32, this is a pointer to the C<HANDLE> value returned
4406fb12b70Safresh1by C<CreateThread> (i.e., C<HANDLE *>); for other platforms, it is a pointer
4416fb12b70Safresh1to the C<pthread_t> structure used in the C<pthread_create> call (i.e.,
4426fb12b70Safresh1C<pthread_t *>).
443898184e3Ssthen
444898184e3SsthenThis method is of no use for general Perl threads programming.  Its intent is
445898184e3Ssthento provide other (XS-based) thread modules with the capability to access, and
446898184e3Ssthenpossibly manipulate, the underlying thread structure associated with a Perl
447898184e3Ssthenthread.
448898184e3Ssthen
449898184e3Ssthen=item threads->_handle()
450898184e3Ssthen
451898184e3SsthenClass method that allows a thread to obtain its own I<handle>.
452898184e3Ssthen
453898184e3Ssthen=back
454898184e3Ssthen
455898184e3Ssthen=head1 EXITING A THREAD
456898184e3Ssthen
457898184e3SsthenThe usual method for terminating a thread is to
458898184e3SsthenL<return()|perlfunc/"return EXPR"> from the entry point function with the
459898184e3Ssthenappropriate return value(s).
460898184e3Ssthen
461898184e3Ssthen=over
462898184e3Ssthen
463898184e3Ssthen=item threads->exit()
464898184e3Ssthen
465898184e3SsthenIf needed, a thread can be exited at any time by calling
466898184e3SsthenC<threads-E<gt>exit()>.  This will cause the thread to return C<undef> in a
467898184e3Ssthenscalar context, or the empty list in a list context.
468898184e3Ssthen
469898184e3SsthenWhen called from the I<main> thread, this behaves the same as C<exit(0)>.
470898184e3Ssthen
471898184e3Ssthen=item threads->exit(status)
472898184e3Ssthen
473898184e3SsthenWhen called from a thread, this behaves like C<threads-E<gt>exit()> (i.e., the
474898184e3Ssthenexit status code is ignored).
475898184e3Ssthen
476898184e3SsthenWhen called from the I<main> thread, this behaves the same as C<exit(status)>.
477898184e3Ssthen
478898184e3Ssthen=item die()
479898184e3Ssthen
480898184e3SsthenCalling C<die()> in a thread indicates an abnormal exit for the thread.  Any
481898184e3SsthenC<$SIG{__DIE__}> handler in the thread will be called first, and then the
482898184e3Ssthenthread will exit with a warning message that will contain any arguments passed
483898184e3Ssthenin the C<die()> call.
484898184e3Ssthen
485898184e3Ssthen=item exit(status)
486898184e3Ssthen
487898184e3SsthenCalling L<exit()|perlfunc/"exit EXPR"> inside a thread causes the whole
488898184e3Ssthenapplication to terminate.  Because of this, the use of C<exit()> inside
489898184e3Ssthenthreaded code, or in modules that might be used in threaded applications, is
490898184e3Ssthenstrongly discouraged.
491898184e3Ssthen
492898184e3SsthenIf C<exit()> really is needed, then consider using the following:
493898184e3Ssthen
494898184e3Ssthen    threads->exit() if threads->can('exit');   # Thread friendly
495898184e3Ssthen    exit(status);
496898184e3Ssthen
497898184e3Ssthen=item use threads 'exit' => 'threads_only'
498898184e3Ssthen
499898184e3SsthenThis globally overrides the default behavior of calling C<exit()> inside a
500898184e3Ssthenthread, and effectively causes such calls to behave the same as
501898184e3SsthenC<threads-E<gt>exit()>.  In other words, with this setting, calling C<exit()>
502898184e3Ssthencauses only the thread to terminate.
503898184e3Ssthen
504898184e3SsthenBecause of its global effect, this setting should not be used inside modules
505898184e3Ssthenor the like.
506898184e3Ssthen
507898184e3SsthenThe I<main> thread is unaffected by this setting.
508898184e3Ssthen
509898184e3Ssthen=item threads->create({'exit' => 'thread_only'}, ...)
510898184e3Ssthen
511898184e3SsthenThis overrides the default behavior of C<exit()> inside the newly created
512898184e3Ssthenthread only.
513898184e3Ssthen
514898184e3Ssthen=item $thr->set_thread_exit_only(boolean)
515898184e3Ssthen
516898184e3SsthenThis can be used to change the I<exit thread only> behavior for a thread after
517898184e3Ssthenit has been created.  With a I<true> argument, C<exit()> will cause only the
518898184e3Ssthenthread to exit.  With a I<false> argument, C<exit()> will terminate the
519898184e3Ssthenapplication.
520898184e3Ssthen
521898184e3SsthenThe I<main> thread is unaffected by this call.
522898184e3Ssthen
523898184e3Ssthen=item threads->set_thread_exit_only(boolean)
524898184e3Ssthen
525898184e3SsthenClass method for use inside a thread to change its own behavior for C<exit()>.
526898184e3Ssthen
527898184e3SsthenThe I<main> thread is unaffected by this call.
528898184e3Ssthen
529898184e3Ssthen=back
530898184e3Ssthen
531898184e3Ssthen=head1 THREAD STATE
532898184e3Ssthen
533898184e3SsthenThe following boolean methods are useful in determining the I<state> of a
534898184e3Ssthenthread.
535898184e3Ssthen
536898184e3Ssthen=over
537898184e3Ssthen
538898184e3Ssthen=item $thr->is_running()
539898184e3Ssthen
540898184e3SsthenReturns true if a thread is still running (i.e., if its entry point function
541898184e3Ssthenhas not yet finished or exited).
542898184e3Ssthen
543898184e3Ssthen=item $thr->is_joinable()
544898184e3Ssthen
545898184e3SsthenReturns true if the thread has finished running, is not detached and has not
546898184e3Ssthenyet been joined.  In other words, the thread is ready to be joined, and a call
547898184e3Ssthento C<$thr-E<gt>join()> will not I<block>.
548898184e3Ssthen
549898184e3Ssthen=item $thr->is_detached()
550898184e3Ssthen
551898184e3SsthenReturns true if the thread has been detached.
552898184e3Ssthen
553898184e3Ssthen=item threads->is_detached()
554898184e3Ssthen
555898184e3SsthenClass method that allows a thread to determine whether or not it is detached.
556898184e3Ssthen
557898184e3Ssthen=back
558898184e3Ssthen
559898184e3Ssthen=head1 THREAD CONTEXT
560898184e3Ssthen
561898184e3SsthenAs with subroutines, the type of value returned from a thread's entry point
562898184e3Ssthenfunction may be determined by the thread's I<context>:  list, scalar or void.
563898184e3SsthenThe thread's context is determined at thread creation.  This is necessary so
564898184e3Ssthenthat the context is available to the entry point function via
565898184e3SsthenL<wantarray()|perlfunc/"wantarray">.  The thread may then specify a value of
566898184e3Ssthenthe appropriate type to be returned from C<-E<gt>join()>.
567898184e3Ssthen
568898184e3Ssthen=head2 Explicit context
569898184e3Ssthen
570898184e3SsthenBecause thread creation and thread joining may occur in different contexts, it
571898184e3Ssthenmay be desirable to state the context explicitly to the thread's entry point
572898184e3Ssthenfunction.  This may be done by calling C<-E<gt>create()> with a hash reference
573898184e3Ssthenas the first argument:
574898184e3Ssthen
575898184e3Ssthen    my $thr = threads->create({'context' => 'list'}, \&foo);
576898184e3Ssthen    ...
577898184e3Ssthen    my @results = $thr->join();
578898184e3Ssthen
579898184e3SsthenIn the above, the threads object is returned to the parent thread in scalar
580898184e3Ssthencontext, and the thread's entry point function C<foo> will be called in list
581898184e3Ssthen(array) context such that the parent thread can receive a list (array) from
582898184e3Ssthenthe C<-E<gt>join()> call.  (C<'array'> is synonymous with C<'list'>.)
583898184e3Ssthen
584898184e3SsthenSimilarly, if you need the threads object, but your thread will not be
585898184e3Ssthenreturning a value (i.e., I<void> context), you would do the following:
586898184e3Ssthen
587898184e3Ssthen    my $thr = threads->create({'context' => 'void'}, \&foo);
588898184e3Ssthen    ...
589898184e3Ssthen    $thr->join();
590898184e3Ssthen
591898184e3SsthenThe context type may also be used as the I<key> in the hash reference followed
592898184e3Ssthenby a I<true> value:
593898184e3Ssthen
594898184e3Ssthen    threads->create({'scalar' => 1}, \&foo);
595898184e3Ssthen    ...
596898184e3Ssthen    my ($thr) = threads->list();
597898184e3Ssthen    my $result = $thr->join();
598898184e3Ssthen
599898184e3Ssthen=head2 Implicit context
600898184e3Ssthen
601898184e3SsthenIf not explicitly stated, the thread's context is implied from the context
602898184e3Ssthenof the C<-E<gt>create()> call:
603898184e3Ssthen
604898184e3Ssthen    # Create thread in list context
605898184e3Ssthen    my ($thr) = threads->create(...);
606898184e3Ssthen
607898184e3Ssthen    # Create thread in scalar context
608898184e3Ssthen    my $thr = threads->create(...);
609898184e3Ssthen
610898184e3Ssthen    # Create thread in void context
611898184e3Ssthen    threads->create(...);
612898184e3Ssthen
613898184e3Ssthen=head2 $thr->wantarray()
614898184e3Ssthen
615898184e3SsthenThis returns the thread's context in the same manner as
616898184e3SsthenL<wantarray()|perlfunc/"wantarray">.
617898184e3Ssthen
618898184e3Ssthen=head2 threads->wantarray()
619898184e3Ssthen
620898184e3SsthenClass method to return the current thread's context.  This returns the same
621898184e3Ssthenvalue as running L<wantarray()|perlfunc/"wantarray"> inside the current
622898184e3Ssthenthread's entry point function.
623898184e3Ssthen
624898184e3Ssthen=head1 THREAD STACK SIZE
625898184e3Ssthen
626898184e3SsthenThe default per-thread stack size for different platforms varies
627898184e3Ssthensignificantly, and is almost always far more than is needed for most
628898184e3Ssthenapplications.  On Win32, Perl's makefile explicitly sets the default stack to
629898184e3Ssthen16 MB; on most other platforms, the system default is used, which again may be
630898184e3Ssthenmuch larger than is needed.
631898184e3Ssthen
632898184e3SsthenBy tuning the stack size to more accurately reflect your application's needs,
633898184e3Ssthenyou may significantly reduce your application's memory usage, and increase the
634898184e3Ssthennumber of simultaneously running threads.
635898184e3Ssthen
636898184e3SsthenNote that on Windows, address space allocation granularity is 64 KB,
637898184e3Ssthentherefore, setting the stack smaller than that on Win32 Perl will not save any
638898184e3Ssthenmore memory.
639898184e3Ssthen
640898184e3Ssthen=over
641898184e3Ssthen
642898184e3Ssthen=item threads->get_stack_size();
643898184e3Ssthen
644898184e3SsthenReturns the current default per-thread stack size.  The default is zero, which
645898184e3Ssthenmeans the system default stack size is currently in use.
646898184e3Ssthen
647898184e3Ssthen=item $size = $thr->get_stack_size();
648898184e3Ssthen
649898184e3SsthenReturns the stack size for a particular thread.  A return value of zero
650898184e3Ssthenindicates the system default stack size was used for the thread.
651898184e3Ssthen
652898184e3Ssthen=item $old_size = threads->set_stack_size($new_size);
653898184e3Ssthen
654898184e3SsthenSets a new default per-thread stack size, and returns the previous setting.
655898184e3Ssthen
656898184e3SsthenSome platforms have a minimum thread stack size.  Trying to set the stack size
657898184e3Ssthenbelow this value will result in a warning, and the minimum stack size will be
658898184e3Ssthenused.
659898184e3Ssthen
660898184e3SsthenSome Linux platforms have a maximum stack size.  Setting too large of a stack
661898184e3Ssthensize will cause thread creation to fail.
662898184e3Ssthen
663898184e3SsthenIf needed, C<$new_size> will be rounded up to the next multiple of the memory
664898184e3Ssthenpage size (usually 4096 or 8192).
665898184e3Ssthen
666898184e3SsthenThreads created after the stack size is set will then either call
667898184e3SsthenC<pthread_attr_setstacksize()> I<(for pthreads platforms)>, or supply the
668898184e3Ssthenstack size to C<CreateThread()> I<(for Win32 Perl)>.
669898184e3Ssthen
670898184e3Ssthen(Obviously, this call does not affect any currently extant threads.)
671898184e3Ssthen
672898184e3Ssthen=item use threads ('stack_size' => VALUE);
673898184e3Ssthen
674898184e3SsthenThis sets the default per-thread stack size at the start of the application.
675898184e3Ssthen
676898184e3Ssthen=item $ENV{'PERL5_ITHREADS_STACK_SIZE'}
677898184e3Ssthen
678898184e3SsthenThe default per-thread stack size may be set at the start of the application
679898184e3Ssthenthrough the use of the environment variable C<PERL5_ITHREADS_STACK_SIZE>:
680898184e3Ssthen
681898184e3Ssthen    PERL5_ITHREADS_STACK_SIZE=1048576
682898184e3Ssthen    export PERL5_ITHREADS_STACK_SIZE
683898184e3Ssthen    perl -e'use threads; print(threads->get_stack_size(), "\n")'
684898184e3Ssthen
685898184e3SsthenThis value overrides any C<stack_size> parameter given to C<use threads>.  Its
686898184e3Ssthenprimary purpose is to permit setting the per-thread stack size for legacy
687898184e3Ssthenthreaded applications.
688898184e3Ssthen
689898184e3Ssthen=item threads->create({'stack_size' => VALUE}, FUNCTION, ARGS)
690898184e3Ssthen
691898184e3SsthenTo specify a particular stack size for any individual thread, call
692898184e3SsthenC<-E<gt>create()> with a hash reference as the first argument:
693898184e3Ssthen
694b8851fccSafresh1    my $thr = threads->create({'stack_size' => 32*4096},
695b8851fccSafresh1                              \&foo, @args);
696898184e3Ssthen
697898184e3Ssthen=item $thr2 = $thr1->create(FUNCTION, ARGS)
698898184e3Ssthen
699898184e3SsthenThis creates a new thread (C<$thr2>) that inherits the stack size from an
700898184e3Ssthenexisting thread (C<$thr1>).  This is shorthand for the following:
701898184e3Ssthen
702898184e3Ssthen    my $stack_size = $thr1->get_stack_size();
703b8851fccSafresh1    my $thr2 = threads->create({'stack_size' => $stack_size},
704b8851fccSafresh1                               FUNCTION, ARGS);
705898184e3Ssthen
706898184e3Ssthen=back
707898184e3Ssthen
708898184e3Ssthen=head1 THREAD SIGNALLING
709898184e3Ssthen
710898184e3SsthenWhen safe signals is in effect (the default behavior - see L</"Unsafe signals">
711898184e3Ssthenfor more details), then signals may be sent and acted upon by individual
712898184e3Ssthenthreads.
713898184e3Ssthen
714898184e3Ssthen=over 4
715898184e3Ssthen
716898184e3Ssthen=item $thr->kill('SIG...');
717898184e3Ssthen
718898184e3SsthenSends the specified signal to the thread.  Signal names and (positive) signal
719898184e3Ssthennumbers are the same as those supported by
720898184e3SsthenL<kill()|perlfunc/"kill SIGNAL, LIST">.  For example, 'SIGTERM', 'TERM' and
721898184e3Ssthen(depending on the OS) 15 are all valid arguments to C<-E<gt>kill()>.
722898184e3Ssthen
723898184e3SsthenReturns the thread object to allow for method chaining:
724898184e3Ssthen
725898184e3Ssthen    $thr->kill('SIG...')->join();
726898184e3Ssthen
727898184e3Ssthen=back
728898184e3Ssthen
729898184e3SsthenSignal handlers need to be set up in the threads for the signals they are
730898184e3Ssthenexpected to act upon.  Here's an example for I<cancelling> a thread:
731898184e3Ssthen
732898184e3Ssthen    use threads;
733898184e3Ssthen
734898184e3Ssthen    sub thr_func
735898184e3Ssthen    {
736898184e3Ssthen        # Thread 'cancellation' signal handler
737898184e3Ssthen        $SIG{'KILL'} = sub { threads->exit(); };
738898184e3Ssthen
739898184e3Ssthen        ...
740898184e3Ssthen    }
741898184e3Ssthen
742898184e3Ssthen    # Create a thread
743898184e3Ssthen    my $thr = threads->create('thr_func');
744898184e3Ssthen
745898184e3Ssthen    ...
746898184e3Ssthen
747898184e3Ssthen    # Signal the thread to terminate, and then detach
748898184e3Ssthen    # it so that it will get cleaned up automatically
749898184e3Ssthen    $thr->kill('KILL')->detach();
750898184e3Ssthen
751898184e3SsthenHere's another simplistic example that illustrates the use of thread
752898184e3Ssthensignalling in conjunction with a semaphore to provide rudimentary I<suspend>
753898184e3Ssthenand I<resume> capabilities:
754898184e3Ssthen
755898184e3Ssthen    use threads;
756898184e3Ssthen    use Thread::Semaphore;
757898184e3Ssthen
758898184e3Ssthen    sub thr_func
759898184e3Ssthen    {
760898184e3Ssthen        my $sema = shift;
761898184e3Ssthen
762898184e3Ssthen        # Thread 'suspend/resume' signal handler
763898184e3Ssthen        $SIG{'STOP'} = sub {
764898184e3Ssthen            $sema->down();      # Thread suspended
765898184e3Ssthen            $sema->up();        # Thread resumes
766898184e3Ssthen        };
767898184e3Ssthen
768898184e3Ssthen        ...
769898184e3Ssthen    }
770898184e3Ssthen
771898184e3Ssthen    # Create a semaphore and pass it to a thread
772898184e3Ssthen    my $sema = Thread::Semaphore->new();
773898184e3Ssthen    my $thr = threads->create('thr_func', $sema);
774898184e3Ssthen
775898184e3Ssthen    # Suspend the thread
776898184e3Ssthen    $sema->down();
777898184e3Ssthen    $thr->kill('STOP');
778898184e3Ssthen
779898184e3Ssthen    ...
780898184e3Ssthen
781898184e3Ssthen    # Allow the thread to continue
782898184e3Ssthen    $sema->up();
783898184e3Ssthen
784898184e3SsthenCAVEAT:  The thread signalling capability provided by this module does not
785898184e3Ssthenactually send signals via the OS.  It I<emulates> signals at the Perl-level
786898184e3Ssthensuch that signal handlers are called in the appropriate thread.  For example,
787898184e3Ssthensending C<$thr-E<gt>kill('STOP')> does not actually suspend a thread (or the
788898184e3Ssthenwhole process), but does cause a C<$SIG{'STOP'}> handler to be called in that
789898184e3Ssthenthread (as illustrated above).
790898184e3Ssthen
791898184e3SsthenAs such, signals that would normally not be appropriate to use in the
792898184e3SsthenC<kill()> command (e.g., C<kill('KILL', $$)>) are okay to use with the
793898184e3SsthenC<-E<gt>kill()> method (again, as illustrated above).
794898184e3Ssthen
795898184e3SsthenCorrespondingly, sending a signal to a thread does not disrupt the operation
796898184e3Ssthenthe thread is currently working on:  The signal will be acted upon after the
797898184e3Ssthencurrent operation has completed.  For instance, if the thread is I<stuck> on
798898184e3Ssthenan I/O call, sending it a signal will not cause the I/O call to be interrupted
799898184e3Ssthensuch that the signal is acted up immediately.
800898184e3Ssthen
8016fb12b70Safresh1Sending a signal to a terminated/finished thread is ignored.
802898184e3Ssthen
803898184e3Ssthen=head1 WARNINGS
804898184e3Ssthen
805898184e3Ssthen=over 4
806898184e3Ssthen
807898184e3Ssthen=item Perl exited with active threads:
808898184e3Ssthen
809898184e3SsthenIf the program exits without all threads having either been joined or
810898184e3Ssthendetached, then this warning will be issued.
811898184e3Ssthen
812898184e3SsthenNOTE:  If the I<main> thread exits, then this warning cannot be suppressed
813898184e3Ssthenusing C<no warnings 'threads';> as suggested below.
814898184e3Ssthen
815898184e3Ssthen=item Thread creation failed: pthread_create returned #
816898184e3Ssthen
817898184e3SsthenSee the appropriate I<man> page for C<pthread_create> to determine the actual
818898184e3Ssthencause for the failure.
819898184e3Ssthen
820898184e3Ssthen=item Thread # terminated abnormally: ...
821898184e3Ssthen
822898184e3SsthenA thread terminated in some manner other than just returning from its entry
823898184e3Ssthenpoint function, or by using C<threads-E<gt>exit()>.  For example, the thread
824898184e3Ssthenmay have terminated because of an error, or by using C<die>.
825898184e3Ssthen
826898184e3Ssthen=item Using minimum thread stack size of #
827898184e3Ssthen
828898184e3SsthenSome platforms have a minimum thread stack size.  Trying to set the stack size
829898184e3Ssthenbelow this value will result in the above warning, and the stack size will be
830898184e3Ssthenset to the minimum.
831898184e3Ssthen
832898184e3Ssthen=item Thread creation failed: pthread_attr_setstacksize(I<SIZE>) returned 22
833898184e3Ssthen
834898184e3SsthenThe specified I<SIZE> exceeds the system's maximum stack size.  Use a smaller
835898184e3Ssthenvalue for the stack size.
836898184e3Ssthen
837898184e3Ssthen=back
838898184e3Ssthen
839898184e3SsthenIf needed, thread warnings can be suppressed by using:
840898184e3Ssthen
841898184e3Ssthen    no warnings 'threads';
842898184e3Ssthen
843898184e3Ssthenin the appropriate scope.
844898184e3Ssthen
845898184e3Ssthen=head1 ERRORS
846898184e3Ssthen
847898184e3Ssthen=over 4
848898184e3Ssthen
849898184e3Ssthen=item This Perl not built to support threads
850898184e3Ssthen
851898184e3SsthenThe particular copy of Perl that you're trying to use was not built using the
852898184e3SsthenC<useithreads> configuration option.
853898184e3Ssthen
854898184e3SsthenHaving threads support requires all of Perl and all of the XS modules in the
855898184e3SsthenPerl installation to be rebuilt; it is not just a question of adding the
856898184e3SsthenL<threads> module (i.e., threaded and non-threaded Perls are binary
8576fb12b70Safresh1incompatible).
858898184e3Ssthen
859898184e3Ssthen=item Cannot change stack size of an existing thread
860898184e3Ssthen
861898184e3SsthenThe stack size of currently extant threads cannot be changed, therefore, the
862898184e3Ssthenfollowing results in the above error:
863898184e3Ssthen
864898184e3Ssthen    $thr->set_stack_size($size);
865898184e3Ssthen
866898184e3Ssthen=item Cannot signal threads without safe signals
867898184e3Ssthen
868898184e3SsthenSafe signals must be in effect to use the C<-E<gt>kill()> signalling method.
869898184e3SsthenSee L</"Unsafe signals"> for more details.
870898184e3Ssthen
871898184e3Ssthen=item Unrecognized signal name: ...
872898184e3Ssthen
873898184e3SsthenThe particular copy of Perl that you're trying to use does not support the
874898184e3Ssthenspecified signal being used in a C<-E<gt>kill()> call.
875898184e3Ssthen
876898184e3Ssthen=back
877898184e3Ssthen
878898184e3Ssthen=head1 BUGS AND LIMITATIONS
879898184e3Ssthen
880898184e3SsthenBefore you consider posting a bug report, please consult, and possibly post a
881898184e3Ssthenmessage to the discussion forum to see if what you've encountered is a known
882898184e3Ssthenproblem.
883898184e3Ssthen
884898184e3Ssthen=over
885898184e3Ssthen
886898184e3Ssthen=item Thread-safe modules
887898184e3Ssthen
888898184e3SsthenSee L<perlmod/"Making your module threadsafe"> when creating modules that may
889898184e3Ssthenbe used in threaded applications, especially if those modules use non-Perl
890898184e3Ssthendata, or XS code.
891898184e3Ssthen
892898184e3Ssthen=item Using non-thread-safe modules
893898184e3Ssthen
894898184e3SsthenUnfortunately, you may encounter Perl modules that are not I<thread-safe>.
895898184e3SsthenFor example, they may crash the Perl interpreter during execution, or may dump
896898184e3Ssthencore on termination.  Depending on the module and the requirements of your
897898184e3Ssthenapplication, it may be possible to work around such difficulties.
898898184e3Ssthen
899898184e3SsthenIf the module will only be used inside a thread, you can try loading the
900898184e3Ssthenmodule from inside the thread entry point function using C<require> (and
901898184e3SsthenC<import> if needed):
902898184e3Ssthen
903898184e3Ssthen    sub thr_func
904898184e3Ssthen    {
905898184e3Ssthen        require Unsafe::Module
906898184e3Ssthen        # Unsafe::Module->import(...);
907898184e3Ssthen
908898184e3Ssthen        ....
909898184e3Ssthen    }
910898184e3Ssthen
911898184e3SsthenIf the module is needed inside the I<main> thread, try modifying your
912898184e3Ssthenapplication so that the module is loaded (again using C<require> and
913898184e3SsthenC<-E<gt>import()>) after any threads are started, and in such a way that no
914898184e3Ssthenother threads are started afterwards.
915898184e3Ssthen
916898184e3SsthenIf the above does not work, or is not adequate for your application, then file
91756d68f1eSafresh1a bug report on L<https://rt.cpan.org/Public/> against the problematic module.
918898184e3Ssthen
919898184e3Ssthen=item Memory consumption
920898184e3Ssthen
921898184e3SsthenOn most systems, frequent and continual creation and destruction of threads
922898184e3Ssthencan lead to ever-increasing growth in the memory footprint of the Perl
923898184e3Sstheninterpreter.  While it is simple to just launch threads and then
924898184e3SsthenC<-E<gt>join()> or C<-E<gt>detach()> them, for long-lived applications, it is
925898184e3Ssthenbetter to maintain a pool of threads, and to reuse them for the work needed,
926898184e3Ssthenusing L<queues|Thread::Queue> to notify threads of pending work.  The CPAN
927898184e3Ssthendistribution of this module contains a simple example
928898184e3Ssthen(F<examples/pool_reuse.pl>) illustrating the creation, use and monitoring of a
929898184e3Ssthenpool of I<reusable> threads.
930898184e3Ssthen
931898184e3Ssthen=item Current working directory
932898184e3Ssthen
933898184e3SsthenOn all platforms except MSWin32, the setting for the current working directory
934898184e3Ssthenis shared among all threads such that changing it in one thread (e.g., using
935898184e3SsthenC<chdir()>) will affect all the threads in the application.
936898184e3Ssthen
937898184e3SsthenOn MSWin32, each thread maintains its own the current working directory
938898184e3Ssthensetting.
939898184e3Ssthen
9409f11ffb7Safresh1=item Locales
9419f11ffb7Safresh1
9429f11ffb7Safresh1Prior to Perl 5.28, locales could not be used with threads, due to various
9439f11ffb7Safresh1race conditions.  Starting in that release, on systems that implement
9449f11ffb7Safresh1thread-safe locale functions, threads can be used, with some caveats.
9459f11ffb7Safresh1This includes Windows starting with Visual Studio 2005, and systems compatible
9469f11ffb7Safresh1with POSIX 2008.  See L<perllocale/Multi-threaded operation>.
9479f11ffb7Safresh1
9489f11ffb7Safresh1Each thread (except the main thread) is started using the C locale.  The main
9499f11ffb7Safresh1thread is started like all other Perl programs; see L<perllocale/ENVIRONMENT>.
9509f11ffb7Safresh1You can switch locales in any thread as often as you like.
9519f11ffb7Safresh1
9529f11ffb7Safresh1If you want to inherit the parent thread's locale, you can, in the parent, set
9539f11ffb7Safresh1a variable like so:
9549f11ffb7Safresh1
9559f11ffb7Safresh1    $foo = POSIX::setlocale(LC_ALL, NULL);
9569f11ffb7Safresh1
9579f11ffb7Safresh1and then pass to threads->create() a sub that closes over C<$foo>.  Then, in
9589f11ffb7Safresh1the child, you say
9599f11ffb7Safresh1
9609f11ffb7Safresh1    POSIX::setlocale(LC_ALL, $foo);
9619f11ffb7Safresh1
9629f11ffb7Safresh1Or you can use the facilities in L<threads::shared> to pass C<$foo>;
9639f11ffb7Safresh1or if the environment hasn't changed, in the child, do
9649f11ffb7Safresh1
9659f11ffb7Safresh1    POSIX::setlocale(LC_ALL, "");
9669f11ffb7Safresh1
967898184e3Ssthen=item Environment variables
968898184e3Ssthen
969898184e3SsthenCurrently, on all platforms except MSWin32, all I<system> calls (e.g., using
970898184e3SsthenC<system()> or back-ticks) made from threads use the environment variable
971898184e3Ssthensettings from the I<main> thread.  In other words, changes made to C<%ENV> in
972898184e3Ssthena thread will not be visible in I<system> calls made by that thread.
973898184e3Ssthen
974898184e3SsthenTo work around this, set environment variables as part of the I<system> call.
975898184e3SsthenFor example:
976898184e3Ssthen
977898184e3Ssthen    my $msg = 'hello';
978898184e3Ssthen    system("FOO=$msg; echo \$FOO");   # Outputs 'hello' to STDOUT
979898184e3Ssthen
980898184e3SsthenOn MSWin32, each thread maintains its own set of environment variables.
981898184e3Ssthen
982898184e3Ssthen=item Catching signals
983898184e3Ssthen
984898184e3SsthenSignals are I<caught> by the main thread (thread ID = 0) of a script.
985898184e3SsthenTherefore, setting up signal handlers in threads for purposes other than
986898184e3SsthenL</"THREAD SIGNALLING"> as documented above will not accomplish what is
987898184e3Ssthenintended.
988898184e3Ssthen
989898184e3SsthenThis is especially true if trying to catch C<SIGALRM> in a thread.  To handle
990898184e3Ssthenalarms in threads, set up a signal handler in the main thread, and then use
991898184e3SsthenL</"THREAD SIGNALLING"> to relay the signal to the thread:
992898184e3Ssthen
993898184e3Ssthen  # Create thread with a task that may time out
9946fb12b70Safresh1  my $thr = threads->create(sub {
995898184e3Ssthen      threads->yield();
996898184e3Ssthen      eval {
997898184e3Ssthen          $SIG{ALRM} = sub { die("Timeout\n"); };
998898184e3Ssthen          alarm(10);
999898184e3Ssthen          ...  # Do work here
1000898184e3Ssthen          alarm(0);
1001898184e3Ssthen      };
1002898184e3Ssthen      if ($@ =~ /Timeout/) {
1003898184e3Ssthen          warn("Task in thread timed out\n");
1004898184e3Ssthen      }
1005898184e3Ssthen  };
1006898184e3Ssthen
1007898184e3Ssthen  # Set signal handler to relay SIGALRM to thread
1008898184e3Ssthen  $SIG{ALRM} = sub { $thr->kill('ALRM') };
1009898184e3Ssthen
1010898184e3Ssthen  ... # Main thread continues working
1011898184e3Ssthen
1012898184e3Ssthen=item Parent-child threads
1013898184e3Ssthen
1014898184e3SsthenOn some platforms, it might not be possible to destroy I<parent> threads while
1015898184e3Ssthenthere are still existing I<child> threads.
1016898184e3Ssthen
1017898184e3Ssthen=item Unsafe signals
1018898184e3Ssthen
1019898184e3SsthenSince Perl 5.8.0, signals have been made safer in Perl by postponing their
1020898184e3Ssthenhandling until the interpreter is in a I<safe> state.  See
1021898184e3SsthenL<perl58delta/"Safe Signals"> and L<perlipc/"Deferred Signals (Safe Signals)">
1022898184e3Ssthenfor more details.
1023898184e3Ssthen
1024898184e3SsthenSafe signals is the default behavior, and the old, immediate, unsafe
1025898184e3Ssthensignalling behavior is only in effect in the following situations:
1026898184e3Ssthen
1027898184e3Ssthen=over 4
1028898184e3Ssthen
1029e0680481Safresh1=item * Perl has been built with C<PERL_OLD_SIGNALS> (see S<C<perl -V>>).
1030898184e3Ssthen
1031b8851fccSafresh1=item * The environment variable C<PERL_SIGNALS> is set to C<unsafe>
1032b8851fccSafresh1(see L<perlrun/"PERL_SIGNALS">).
1033898184e3Ssthen
1034898184e3Ssthen=item * The module L<Perl::Unsafe::Signals> is used.
1035898184e3Ssthen
1036898184e3Ssthen=back
1037898184e3Ssthen
1038898184e3SsthenIf unsafe signals is in effect, then signal handling is not thread-safe, and
1039898184e3Ssthenthe C<-E<gt>kill()> signalling method cannot be used.
1040898184e3Ssthen
10419f11ffb7Safresh1=item Identity of objects returned from threads
1042898184e3Ssthen
10439f11ffb7Safresh1When a value is returned from a thread through a C<join> operation,
10449f11ffb7Safresh1the value and everything that it references is copied across to the
10459f11ffb7Safresh1joining thread, in much the same way that values are copied upon thread
10469f11ffb7Safresh1creation.  This works fine for most kinds of value, including arrays,
10479f11ffb7Safresh1hashes, and subroutines.  The copying recurses through array elements,
10489f11ffb7Safresh1reference scalars, variables closed over by subroutines, and other kinds
10499f11ffb7Safresh1of reference.
1050898184e3Ssthen
10519f11ffb7Safresh1However, everything referenced by the returned value is a fresh copy in
10529f11ffb7Safresh1the joining thread, even if a returned object had in the child thread
10539f11ffb7Safresh1been a copy of something that previously existed in the parent thread.
10549f11ffb7Safresh1After joining, the parent will therefore have a duplicate of each such
10559f11ffb7Safresh1object.  This sometimes matters, especially if the object gets mutated;
10569f11ffb7Safresh1this can especially matter for private data to which a returned subroutine
10579f11ffb7Safresh1provides access.
1058898184e3Ssthen
10599f11ffb7Safresh1=item Returning blessed objects from threads
10609f11ffb7Safresh1
10619f11ffb7Safresh1Returning blessed objects from threads does not work.  Depending on the classes
1062898184e3Sstheninvolved, you may be able to work around this by returning a serialized
1063898184e3Ssthenversion of the object (e.g., using L<Data::Dumper> or L<Storable>), and then
1064898184e3Ssthenreconstituting it in the joining thread.  If you're using Perl 5.10.0 or
1065898184e3Ssthenlater, and if the class supports L<shared objects|threads::shared/"OBJECTS">,
1066898184e3Ssthenyou can pass them via L<shared queues|Thread::Queue>.
1067898184e3Ssthen
1068898184e3Ssthen=item END blocks in threads
1069898184e3Ssthen
1070898184e3SsthenIt is possible to add L<END blocks|perlmod/"BEGIN, UNITCHECK, CHECK, INIT and
1071898184e3SsthenEND"> to threads by using L<require|perlfunc/"require VERSION"> or
1072898184e3SsthenL<eval|perlfunc/"eval EXPR"> with the appropriate code.  These C<END> blocks
1073898184e3Ssthenwill then be executed when the thread's interpreter is destroyed (i.e., either
1074898184e3Ssthenduring a C<-E<gt>join()> call, or at program termination).
1075898184e3Ssthen
1076898184e3SsthenHowever, calling any L<threads> methods in such an C<END> block will most
1077898184e3Ssthenlikely I<fail> (e.g., the application may hang, or generate an error) due to
1078898184e3Ssthenmutexes that are needed to control functionality within the L<threads> module.
1079898184e3Ssthen
1080898184e3SsthenFor this reason, the use of C<END> blocks in threads is B<strongly>
1081898184e3Ssthendiscouraged.
1082898184e3Ssthen
1083898184e3Ssthen=item Open directory handles
1084898184e3Ssthen
1085898184e3SsthenIn perl 5.14 and higher, on systems other than Windows that do
1086898184e3Ssthennot support the C<fchdir> C function, directory handles (see
1087898184e3SsthenL<opendir|perlfunc/"opendir DIRHANDLE,EXPR">) will not be copied to new
1088898184e3Ssthenthreads. You can use the C<d_fchdir> variable in L<Config.pm|Config> to
1089898184e3Ssthendetermine whether your system supports it.
1090898184e3Ssthen
1091898184e3SsthenIn prior perl versions, spawning threads with open directory handles would
1092898184e3Ssthencrash the interpreter.
109356d68f1eSafresh1L<[perl #75154]|https://rt.perl.org/rt3/Public/Bug/Display.html?id=75154>
1094898184e3Ssthen
10959f11ffb7Safresh1=item Detached threads and global destruction
10969f11ffb7Safresh1
10979f11ffb7Safresh1If the main thread exits while there are detached threads which are still
10989f11ffb7Safresh1running, then Perl's global destruction phase is not executed because
10999f11ffb7Safresh1otherwise certain global structures that control the operation of threads and
11009f11ffb7Safresh1that are allocated in the main thread's memory may get destroyed before the
11019f11ffb7Safresh1detached thread is destroyed.
11029f11ffb7Safresh1
11039f11ffb7Safresh1If you are using any code that requires the execution of the global
11049f11ffb7Safresh1destruction phase for clean up (e.g., removing temp files), then do not use
11059f11ffb7Safresh1detached threads, but rather join all threads before exiting the program.
11069f11ffb7Safresh1
1107898184e3Ssthen=item Perl Bugs and the CPAN Version of L<threads>
1108898184e3Ssthen
1109898184e3SsthenSupport for threads extends beyond the code in this module (i.e.,
1110898184e3SsthenF<threads.pm> and F<threads.xs>), and into the Perl interpreter itself.  Older
1111898184e3Ssthenversions of Perl contain bugs that may manifest themselves despite using the
1112898184e3Ssthenlatest version of L<threads> from CPAN.  There is no workaround for this other
1113898184e3Ssthenthan upgrading to the latest version of Perl.
1114898184e3Ssthen
1115898184e3SsthenEven with the latest version of Perl, it is known that certain constructs
1116898184e3Ssthenwith threads may result in warning messages concerning leaked scalars or
1117898184e3Ssthenunreferenced scalars.  However, such warnings are harmless, and may safely be
1118898184e3Ssthenignored.
1119898184e3Ssthen
1120898184e3SsthenYou can search for L<threads> related bug reports at
112156d68f1eSafresh1L<https://rt.cpan.org/Public/>.  If needed submit any new bugs, problems,
112256d68f1eSafresh1patches, etc. to: L<https://rt.cpan.org/Public/Dist/Display.html?Name=threads>
1123898184e3Ssthen
1124898184e3Ssthen=back
1125898184e3Ssthen
1126898184e3Ssthen=head1 REQUIREMENTS
1127898184e3Ssthen
1128898184e3SsthenPerl 5.8.0 or later
1129898184e3Ssthen
1130898184e3Ssthen=head1 SEE ALSO
1131898184e3Ssthen
11329f11ffb7Safresh1threads on MetaCPAN:
11339f11ffb7Safresh1L<https://metacpan.org/release/threads>
11349f11ffb7Safresh1
11359f11ffb7Safresh1Code repository for CPAN distribution:
11369f11ffb7Safresh1L<https://github.com/Dual-Life/threads>
1137898184e3Ssthen
1138898184e3SsthenL<threads::shared>, L<perlthrtut>
1139898184e3Ssthen
114056d68f1eSafresh1L<https://www.perl.com/pub/a/2002/06/11/threads.html> and
114156d68f1eSafresh1L<https://www.perl.com/pub/a/2002/09/04/threads.html>
1142898184e3Ssthen
1143898184e3SsthenPerl threads mailing list:
114456d68f1eSafresh1L<https://lists.perl.org/list/ithreads.html>
1145898184e3Ssthen
1146898184e3SsthenStack size discussion:
114756d68f1eSafresh1L<https://www.perlmonks.org/?node_id=532956>
1148898184e3Ssthen
11499f11ffb7Safresh1Sample code in the I<examples> directory of this distribution on CPAN.
11509f11ffb7Safresh1
1151898184e3Ssthen=head1 AUTHOR
1152898184e3Ssthen
1153898184e3SsthenArtur Bergman E<lt>sky AT crucially DOT netE<gt>
1154898184e3Ssthen
1155898184e3SsthenCPAN version produced by Jerry D. Hedden <jdhedden AT cpan DOT org>
1156898184e3Ssthen
1157898184e3Ssthen=head1 LICENSE
1158898184e3Ssthen
1159898184e3Ssthenthreads is released under the same license as Perl.
1160898184e3Ssthen
1161898184e3Ssthen=head1 ACKNOWLEDGEMENTS
1162898184e3Ssthen
1163898184e3SsthenRichard Soderberg E<lt>perl AT crystalflame DOT netE<gt> -
1164898184e3SsthenHelping me out tons, trying to find reasons for races and other weird bugs!
1165898184e3Ssthen
1166898184e3SsthenSimon Cozens E<lt>simon AT brecon DOT co DOT ukE<gt> -
1167898184e3SsthenBeing there to answer zillions of annoying questions
1168898184e3Ssthen
1169898184e3SsthenRocco Caputo E<lt>troc AT netrus DOT netE<gt>
1170898184e3Ssthen
1171898184e3SsthenVipul Ved Prakash E<lt>mail AT vipul DOT netE<gt> -
1172898184e3SsthenHelping with debugging
1173898184e3Ssthen
1174898184e3SsthenDean Arnold E<lt>darnold AT presicient DOT comE<gt> -
1175898184e3SsthenStack size API
1176898184e3Ssthen
1177898184e3Ssthen=cut
1178