📄 threads.pm
字号:
=item $thr->kill('SIG...');Sends the specified signal to the thread. Signal names and (positive) signalnumbers are the same as those supported byL<kill()|perlfunc/"kill SIGNAL, LIST">. For example, 'SIGTERM', 'TERM' and(depending on the OS) 15 are all valid arguments to C<-E<gt>kill()>.Returns the thread object to allow for method chaining: $thr->kill('SIG...')->join();=backSignal handlers need to be set up in the threads for the signals they areexpected to act upon. Here's an example for I<cancelling> a thread: use threads; sub thr_func { # Thread 'cancellation' signal handler $SIG{'KILL'} = sub { threads->exit(); }; ... } # Create a thread my $thr = threads->create('thr_func'); ... # Signal the thread to terminate, and then detach # it so that it will get cleaned up automatically $thr->kill('KILL')->detach();Here's another simplistic example that illustrates the use of threadsignalling in conjunction with a semaphore to provide rudimentary I<suspend>and I<resume> capabilities: use threads; use Thread::Semaphore; sub thr_func { my $sema = shift; # Thread 'suspend/resume' signal handler $SIG{'STOP'} = sub { $sema->down(); # Thread suspended $sema->up(); # Thread resumes }; ... } # Create a semaphore and pass it to a thread my $sema = Thread::Semaphore->new(); my $thr = threads->create('thr_func', $sema); # Suspend the thread $sema->down(); $thr->kill('STOP'); ... # Allow the thread to continue $sema->up();CAVEAT: The thread signalling capability provided by this module does notactually send signals via the OS. It I<emulates> signals at the Perl-levelsuch that signal handlers are called in the appropriate thread. For example,sending C<$thr-E<gt>kill('STOP')> does not actually suspend a thread (or thewhole process), but does cause a C<$SIG{'STOP'}> handler to be called in thatthread (as illustrated above).As such, signals that would normally not be appropriate to use in theC<kill()> command (e.g., C<kill('KILL', $$)>) are okay to use with theC<-E<gt>kill()> method (again, as illustrated above).Correspondingly, sending a signal to a thread does not disrupt the operationthe thread is currently working on: The signal will be acted upon after thecurrent operation has completed. For instance, if the thread is I<stuck> onan I/O call, sending it a signal will not cause the I/O call to be interruptedsuch that the signal is acted up immediately.Sending a signal to a terminated thread is ignored.=head1 WARNINGS=over 4=item Perl exited with active threads:If the program exits without all threads having either been joined ordetached, then this warning will be issued.NOTE: If the I<main> thread exits, then this warning cannot be suppressedusing C<no warnings 'threads';> as suggested below.=item Thread creation failed: pthread_create returned #See the appropriate I<man> page for C<pthread_create> to determine the actualcause for the failure.=item Thread # terminated abnormally: ...A thread terminated in some manner other than just returning from its entrypoint function, or by using C<threads-E<gt>exit()>. For example, the threadmay have terminated because of an error, or by using C<die>.=item Using minimum thread stack size of #Some platforms have a minimum thread stack size. Trying to set the stack sizebelow this value will result in the above warning, and the stack size will beset to the minimum.=item Thread creation failed: pthread_attr_setstacksize(I<SIZE>) returned 22The specified I<SIZE> exceeds the system's maximum stack size. Use a smallervalue for the stack size.=backIf needed, thread warnings can be suppressed by using: no warnings 'threads';in the appropriate scope.=head1 ERRORS=over 4=item This Perl not built to support threadsThe particular copy of Perl that you're trying to use was not built using theC<useithreads> configuration option.Having threads support requires all of Perl and all of the XS modules in thePerl installation to be rebuilt; it is not just a question of adding theL<threads> module (i.e., threaded and non-threaded Perls are binaryincompatible.)=item Cannot change stack size of an existing threadThe stack size of currently extant threads cannot be changed, therefore, thefollowing results in the above error: $thr->set_stack_size($size);=item Cannot signal threads without safe signalsSafe signals must be in effect to use the C<-E<gt>kill()> signalling method.See L</"Unsafe signals"> for more details.=item Unrecognized signal name: ...The particular copy of Perl that you're trying to use does not support thespecified signal being used in a C<-E<gt>kill()> call.=back=head1 BUGS AND LIMITATIONSBefore you consider posting a bug report, please consult, and possibly post amessage to the discussion forum to see if what you've encountered is a knownproblem.=over=item Thread-safe modulesSee L<perlmod/"Making your module threadsafe"> when creating modules that maybe used in threaded applications, especially if those modules use non-Perldata, or XS code.=item Using non-thread-safe modulesUnfortunately, you may encounter Perl modules that are not I<thread-safe>.For example, they may crash the Perl interpreter during execution, or may dumpcore on termination. Depending on the module and the requirements of yourapplication, it may be possible to work around such difficulties.If the module will only be used inside a thread, you can try loading themodule from inside the thread entry point function using C<require> (andC<import> if needed): sub thr_func { require Unsafe::Module # Unsafe::Module->import(...); .... }If the module is needed inside the I<main> thread, try modifying yourapplication so that the module is loaded (again using C<require> andC<-E<gt>import()>) after any threads are started, and in such a way that noother threads are started afterwards.If the above does not work, or is not adequate for your application, then filea bug report on L<http://rt.cpan.org/Public/> against the problematic module.=item Current working directoryOn all platforms except MSWin32, the setting for the current working directoryis shared among all threads such that changing it in one thread (e.g., usingC<chdir()>) will affect all the threads in the application.On MSWin32, each thread maintains its own the current working directorysetting.=item Environment variablesCurrently, on all platforms except MSWin32, all I<system> calls (e.g., usingC<system()> or back-ticks) made from threads use the environment variablesettings from the I<main> thread. In other words, changes made to C<%ENV> ina thread will not be visible in I<system> calls made by that thread.To work around this, set environment variables as part of the I<system> call.For example: my $msg = 'hello'; system("FOO=$msg; echo \$FOO"); # Outputs 'hello' to STDOUTOn MSWin32, each thread maintains its own set of environment variables.=item Parent-child threadsOn some platforms, it might not be possible to destroy I<parent> threads whilethere are still existing I<child> threads.=item Creating threads inside special blocksCreating threads inside C<BEGIN>, C<CHECK> or C<INIT> blocks should not berelied upon. Depending on the Perl version and the application code, resultsmay range from success, to (apparently harmless) warnings of leaked scalar, orall the way up to crashing of the Perl interpreter.=item Unsafe signalsSince Perl 5.8.0, signals have been made safer in Perl by postponing theirhandling until the interpreter is in a I<safe> state. SeeL<perl58delta/"Safe Signals"> and L<perlipc/"Deferred Signals (Safe Signals)">for more details.Safe signals is the default behavior, and the old, immediate, unsafesignalling behavior is only in effect in the following situations:=over 4=item * Perl has been built with C<PERL_OLD_SIGNALS> (see C<perl -V>).=item * The environment variable C<PERL_SIGNALS> is set to C<unsafe> (see L<perlrun/"PERL_SIGNALS">).=item * The module L<Perl::Unsafe::Signals> is used.=backIf unsafe signals is in effect, then signal handling is not thread-safe, andthe C<-E<gt>kill()> signalling method cannot be used.=item Returning closures from threadsReturning closures from threads should not be relied upon. Depending of thePerl version and the application code, results may range from success, to(apparently harmless) warnings of leaked scalar, or all the way up to crashingof the Perl interpreter.=item Returning objects from threadsReturning objects from threads does not work. Depending on the classesinvolved, you may be able to work around this by returning a serializedversion of the object (e.g., using L<Data::Dumper> or L<Storable>), and thenreconstituting it in the joining thread.=item Perl Bugs and the CPAN Version of L<threads>Support for threads extends beyond the code in this module (i.e.,F<threads.pm> and F<threads.xs>), and into the Perl interpreter itself. Olderversions of Perl contain bugs that may manifest themselves despite using thelatest version of L<threads> from CPAN. There is no workaround for this otherthan upgrading to the latest version of Perl.Even with the latest version of Perl, it is known that certain constructswith threads may result in warning messages concerning leaked scalars orunreferenced scalars. However, such warnings are harmless, and may safely beignored.=back=head1 REQUIREMENTSPerl 5.8.0 or later=head1 SEE ALSOL<threads> Discussion Forum on CPAN:L<http://www.cpanforum.com/dist/threads>Annotated POD for L<threads>:L<http://annocpan.org/~JDHEDDEN/threads-1.67/threads.pm>Source repository:L<http://code.google.com/p/threads-shared/>L<threads::shared>, L<perlthrtut>L<http://www.perl.com/pub/a/2002/06/11/threads.html> andL<http://www.perl.com/pub/a/2002/09/04/threads.html>Perl threads mailing list:L<http://lists.cpan.org/showlist.cgi?name=iThreads>Stack size discussion:L<http://www.perlmonks.org/?node_id=532956>=head1 AUTHORArtur Bergman E<lt>sky AT crucially DOT netE<gt>threads is released under the same license as Perl.CPAN version produced by Jerry D. Hedden <jdhedden AT cpan DOT org>=head1 ACKNOWLEDGEMENTSRichard Soderberg E<lt>perl AT crystalflame DOT netE<gt> -Helping me out tons, trying to find reasons for races and other weird bugs!Simon Cozens E<lt>simon AT brecon DOT co DOT ukE<gt> -Being there to answer zillions of annoying questionsRocco Caputo E<lt>troc AT netrus DOT netE<gt>Vipul Ved Prakash E<lt>mail AT vipul DOT netE<gt> -Helping with debuggingDean Arnold E<lt>darnold AT presicient DOT comE<gt> -Stack size API=cut
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -