📄 threads.pm
字号:
use threads qw(stringify); my $thr = threads->create(...); print("Thread $thr started...\n"); # Prints out: Thread 1 started...=item threads->object($tid)This will return the I<threads> object for the I<active> thread associatedwith the specified thread ID. Returns C<undef> if there is no threadassociated with the TID, if the thread is joined or detached, if no TID isspecified or if the specified TID is undef.=item threads->yield()This is a suggestion to the OS to let this thread yield CPU time to otherthreads. What actually happens is highly dependent upon the underlyingthread implementation.You may do C<use threads qw(yield)>, and then just use C<yield()> in yourcode.=item threads->list()=item threads->list(threads::all)=item threads->list(threads::running)=item threads->list(threads::joinable)With no arguments (or using C<threads::all>) and in a list context, returns alist of all non-joined, non-detached I<threads> objects. In a scalar context,returns a count of the same.With a I<true> argument (using C<threads::running>), returns a list of allnon-joined, non-detached I<threads> objects that are still running.With a I<false> argument (using C<threads::joinable>), returns a list of allnon-joined, non-detached I<threads> objects that have finished running (i.e.,for which C<-E<gt>join()> will not I<block>).=item $thr1->equal($thr2)Tests if two threads objects are the same thread or not. This is overloadedto the more natural forms: if ($thr1 == $thr2) { print("Threads are the same\n"); } # or if ($thr1 != $thr2) { print("Threads differ\n"); }(Thread comparison is based on thread IDs.)=item async BLOCK;C<async> creates a thread to execute the block immediately followingit. This block is treated as an anonymous subroutine, and so must have asemicolon after the closing brace. Like C<threads-E<gt>create()>, C<async>returns a I<threads> object.=item $thr->error()Threads are executed in an C<eval> context. This method will return C<undef>if the thread terminates I<normally>. Otherwise, it returns the value ofC<$@> associated with the thread's execution status in its C<eval> context.=item $thr->_handle()This I<private> method returns the memory location of the internal threadstructure associated with a threads object. For Win32, this is a pointer tothe C<HANDLE> value returned by C<CreateThread> (i.e., C<HANDLE *>); for otherplatforms, it is a pointer to the C<pthread_t> structure used in theC<pthread_create> call (i.e., C<pthread_t *>).This method is of no use for general Perl threads programming. Its intent isto provide other (XS-based) thread modules with the capability to access, andpossibly manipulate, the underlying thread structure associated with a Perlthread.=item threads->_handle()Class method that allows a thread to obtain its own I<handle>.=back=head1 EXITING A THREADThe usual method for terminating a thread is toL<return()|perlfunc/"return EXPR"> from the entry point function with theappropriate return value(s).=over=item threads->exit()If needed, a thread can be exited at any time by callingC<threads-E<gt>exit()>. This will cause the thread to return C<undef> in ascalar context, or the empty list in a list context.When called from the I<main> thread, this behaves the same as C<exit(0)>.=item threads->exit(status)When called from a thread, this behaves like C<threads-E<gt>exit()> (i.e., theexit status code is ignored).When called from the I<main> thread, this behaves the same as C<exit(status)>.=item die()Calling C<die()> in a thread indicates an abnormal exit for the thread. AnyC<$SIG{__DIE__}> handler in the thread will be called first, and then thethread will exit with a warning message that will contain any arguments passedin the C<die()> call.=item exit(status)Calling L<exit()|perlfunc/"exit EXPR"> inside a thread causes the wholeapplication to terminate. Because of this, the use of C<exit()> insidethreaded code, or in modules that might be used in threaded applications, isstrongly discouraged.If C<exit()> really is needed, then consider using the following: threads->exit() if threads->can('exit'); # Thread friendly exit(status);=item use threads 'exit' => 'threads_only'This globally overrides the default behavior of calling C<exit()> inside athread, and effectively causes such calls to behave the same asC<threads-E<gt>exit()>. In other words, with this setting, calling C<exit()>causes only the thread to terminate.Because of its global effect, this setting should not be used inside modulesor the like.The I<main> thread is unaffected by this setting.=item threads->create({'exit' => 'thread_only'}, ...)This overrides the default behavior of C<exit()> inside the newly createdthread only.=item $thr->set_thread_exit_only(boolean)This can be used to change the I<exit thread only> behavior for a thread afterit has been created. With a I<true> argument, C<exit()> will cause only thethread to exit. With a I<false> argument, C<exit()> will terminate theapplication.The I<main> thread is unaffected by this call.=item threads->set_thread_exit_only(boolean)Class method for use inside a thread to change its own behavior for C<exit()>.The I<main> thread is unaffected by this call.=back=head1 THREAD STATEThe following boolean methods are useful in determining the I<state> of athread.=over=item $thr->is_running()Returns true if a thread is still running (i.e., if its entry point functionhas not yet finished or exited).=item $thr->is_joinable()Returns true if the thread has finished running, is not detached and has notyet been joined. In other words, the thread is ready to be joined, and a callto C<$thr-E<gt>join()> will not I<block>.=item $thr->is_detached()Returns true if the thread has been detached.=item threads->is_detached()Class method that allows a thread to determine whether or not it is detached.=back=head1 THREAD CONTEXTAs with subroutines, the type of value returned from a thread's entry pointfunction may be determined by the thread's I<context>: list, scalar or void.The thread's context is determined at thread creation. This is necessary sothat the context is available to the entry point function viaL<wantarray()|perlfunc/"wantarray">. The thread may then specify a value ofthe appropriate type to be returned from C<-E<gt>join()>.=head2 Explicit contextBecause thread creation and thread joining may occur in different contexts, itmay be desirable to state the context explicitly to the thread's entry pointfunction. This may be done by calling C<-E<gt>create()> with a hash referenceas the first argument: my $thr = threads->create({'context' => 'list'}, \&foo); ... my @results = $thr->join();In the above, the threads object is returned to the parent thread in scalarcontext, and the thread's entry point function C<foo> will be called in list(array) context such that the parent thread can receive a list (array) fromthe C<-E<gt>join()> call. (C<'array'> is synonymous with C<'list'>.)Similarly, if you need the threads object, but your thread will not bereturning a value (i.e., I<void> context), you would do the following: my $thr = threads->create({'context' => 'void'}, \&foo); ... $thr->join();The context type may also be used as the I<key> in the hash reference followedby a I<true> value: threads->create({'scalar' => 1}, \&foo); ... my ($thr) = threads->list(); my $result = $thr->join();=head2 Implicit contextIf not explicitly stated, the thread's context is implied from the contextof the C<-E<gt>create()> call: # Create thread in list context my ($thr) = threads->create(...); # Create thread in scalar context my $thr = threads->create(...); # Create thread in void context threads->create(...);=head2 $thr->wantarray()This returns the thread's context in the same manner asL<wantarray()|perlfunc/"wantarray">.=head2 threads->wantarray()Class method to return the current thread's context. This returns the samevalue as running L<wantarray()|perlfunc/"wantarray"> inside the currentthread's entry point function.=head1 THREAD STACK SIZEThe default per-thread stack size for different platforms variessignificantly, and is almost always far more than is needed for mostapplications. On Win32, Perl's makefile explicitly sets the default stack to16 MB; on most other platforms, the system default is used, which again may bemuch larger than is needed.By tuning the stack size to more accurately reflect your application's needs,you may significantly reduce your application's memory usage, and increase thenumber of simultaneously running threads.Note that on Windows, address space allocation granularity is 64 KB,therefore, setting the stack smaller than that on Win32 Perl will not save anymore memory.=over=item threads->get_stack_size();Returns the current default per-thread stack size. The default is zero, whichmeans the system default stack size is currently in use.=item $size = $thr->get_stack_size();Returns the stack size for a particular thread. A return value of zeroindicates the system default stack size was used for the thread.=item $old_size = threads->set_stack_size($new_size);Sets a new default per-thread stack size, and returns the previous setting.Some platforms have a minimum thread stack size. Trying to set the stack sizebelow this value will result in a warning, and the minimum stack size will beused.Some Linux platforms have a maximum stack size. Setting too large of a stacksize will cause thread creation to fail.If needed, C<$new_size> will be rounded up to the next multiple of the memorypage size (usually 4096 or 8192).Threads created after the stack size is set will then either callC<pthread_attr_setstacksize()> I<(for pthreads platforms)>, or supply thestack size to C<CreateThread()> I<(for Win32 Perl)>.(Obviously, this call does not affect any currently extant threads.)=item use threads ('stack_size' => VALUE);This sets the default per-thread stack size at the start of the application.=item $ENV{'PERL5_ITHREADS_STACK_SIZE'}The default per-thread stack size may be set at the start of the applicationthrough the use of the environment variable C<PERL5_ITHREADS_STACK_SIZE>: PERL5_ITHREADS_STACK_SIZE=1048576 export PERL5_ITHREADS_STACK_SIZE perl -e'use threads; print(threads->get_stack_size(), "\n")'This value overrides any C<stack_size> parameter given to C<use threads>. Itsprimary purpose is to permit setting the per-thread stack size for legacythreaded applications.=item threads->create({'stack_size' => VALUE}, FUNCTION, ARGS)To specify a particular stack size for any individual thread, callC<-E<gt>create()> with a hash reference as the first argument: my $thr = threads->create({'stack_size' => 32*4096}, \&foo, @args);=item $thr2 = $thr1->create(FUNCTION, ARGS)This creates a new thread (C<$thr2>) that inherits the stack size from anexisting thread (C<$thr1>). This is shorthand for the following: my $stack_size = $thr1->get_stack_size(); my $thr2 = threads->create({'stack_size' => $stack_size}, FUNCTION, ARGS);=back=head1 THREAD SIGNALLINGWhen safe signals is in effect (the default behavior - see L</"Unsafe signals">for more details), then signals may be sent and acted upon by individualthreads.=over 4
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -