threads.pm 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127
  1. package threads;
  2. use 5.008;
  3. use strict;
  4. use warnings;
  5. our $VERSION = '2.01';
  6. my $XS_VERSION = $VERSION;
  7. $VERSION = eval $VERSION;
  8. # Verify this Perl supports threads
  9. require Config;
  10. if (! $Config::Config{useithreads}) {
  11. die("This Perl not built to support threads\n");
  12. }
  13. # Complain if 'threads' is loaded after 'threads::shared'
  14. if ($threads::shared::threads_shared) {
  15. warn <<'_MSG_';
  16. Warning, threads::shared has already been loaded. To
  17. enable shared variables, 'use threads' must be called
  18. before threads::shared or any module that uses it.
  19. _MSG_
  20. }
  21. # Declare that we have been loaded
  22. $threads::threads = 1;
  23. # Load the XS code
  24. require XSLoader;
  25. XSLoader::load('threads', $XS_VERSION);
  26. ### Export ###
  27. sub import
  28. {
  29. my $class = shift; # Not used
  30. # Exported subroutines
  31. my @EXPORT = qw(async);
  32. # Handle args
  33. while (my $sym = shift) {
  34. if ($sym =~ /^(?:stack|exit)/i) {
  35. if (defined(my $arg = shift)) {
  36. if ($sym =~ /^stack/i) {
  37. threads->set_stack_size($arg);
  38. } else {
  39. $threads::thread_exit_only = $arg =~ /^thread/i;
  40. }
  41. } else {
  42. require Carp;
  43. Carp::croak("threads: Missing argument for option: $sym");
  44. }
  45. } elsif ($sym =~ /^str/i) {
  46. import overload ('""' => \&tid);
  47. } elsif ($sym =~ /^(?::all|yield)$/) {
  48. push(@EXPORT, qw(yield));
  49. } else {
  50. require Carp;
  51. Carp::croak("threads: Unknown import option: $sym");
  52. }
  53. }
  54. # Export subroutine names
  55. my $caller = caller();
  56. foreach my $sym (@EXPORT) {
  57. no strict 'refs';
  58. *{$caller.'::'.$sym} = \&{$sym};
  59. }
  60. # Set stack size via environment variable
  61. if (exists($ENV{'PERL5_ITHREADS_STACK_SIZE'})) {
  62. threads->set_stack_size($ENV{'PERL5_ITHREADS_STACK_SIZE'});
  63. }
  64. }
  65. ### Methods, etc. ###
  66. # Exit from a thread (only)
  67. sub exit
  68. {
  69. my ($class, $status) = @_;
  70. if (! defined($status)) {
  71. $status = 0;
  72. }
  73. # Class method only
  74. if (ref($class)) {
  75. require Carp;
  76. Carp::croak('Usage: threads->exit(status)');
  77. }
  78. $class->set_thread_exit_only(1);
  79. CORE::exit($status);
  80. }
  81. # 'Constant' args for threads->list()
  82. sub threads::all { }
  83. sub threads::running { 1 }
  84. sub threads::joinable { 0 }
  85. # 'new' is an alias for 'create'
  86. *new = \&create;
  87. # 'async' is a function alias for the 'threads->create()' method
  88. sub async (&;@)
  89. {
  90. unshift(@_, 'threads');
  91. # Use "goto" trick to avoid pad problems from 5.8.1 (fixed in 5.8.2)
  92. goto &create;
  93. }
  94. # Thread object equality checking
  95. use overload (
  96. '==' => \&equal,
  97. '!=' => sub { ! equal(@_) },
  98. 'fallback' => 1
  99. );
  100. 1;
  101. __END__
  102. =head1 NAME
  103. threads - Perl interpreter-based threads
  104. =head1 VERSION
  105. This document describes threads version 2.01
  106. =head1 WARNING
  107. The "interpreter-based threads" provided by Perl are not the fast, lightweight
  108. system for multitasking that one might expect or hope for. Threads are
  109. implemented in a way that make them easy to misuse. Few people know how to
  110. use them correctly or will be able to provide help.
  111. The use of interpreter-based threads in perl is officially
  112. L<discouraged|perlpolicy/discouraged>.
  113. =head1 SYNOPSIS
  114. use threads ('yield',
  115. 'stack_size' => 64*4096,
  116. 'exit' => 'threads_only',
  117. 'stringify');
  118. sub start_thread {
  119. my @args = @_;
  120. print('Thread started: ', join(' ', @args), "\n");
  121. }
  122. my $thr = threads->create('start_thread', 'argument');
  123. $thr->join();
  124. threads->create(sub { print("I am a thread\n"); })->join();
  125. my $thr2 = async { foreach (@files) { ... } };
  126. $thr2->join();
  127. if (my $err = $thr2->error()) {
  128. warn("Thread error: $err\n");
  129. }
  130. # Invoke thread in list context (implicit) so it can return a list
  131. my ($thr) = threads->create(sub { return (qw/a b c/); });
  132. # or specify list context explicitly
  133. my $thr = threads->create({'context' => 'list'},
  134. sub { return (qw/a b c/); });
  135. my @results = $thr->join();
  136. $thr->detach();
  137. # Get a thread's object
  138. $thr = threads->self();
  139. $thr = threads->object($tid);
  140. # Get a thread's ID
  141. $tid = threads->tid();
  142. $tid = $thr->tid();
  143. $tid = "$thr";
  144. # Give other threads a chance to run
  145. threads->yield();
  146. yield();
  147. # Lists of non-detached threads
  148. my @threads = threads->list();
  149. my $thread_count = threads->list();
  150. my @running = threads->list(threads::running);
  151. my @joinable = threads->list(threads::joinable);
  152. # Test thread objects
  153. if ($thr1 == $thr2) {
  154. ...
  155. }
  156. # Manage thread stack size
  157. $stack_size = threads->get_stack_size();
  158. $old_size = threads->set_stack_size(32*4096);
  159. # Create a thread with a specific context and stack size
  160. my $thr = threads->create({ 'context' => 'list',
  161. 'stack_size' => 32*4096,
  162. 'exit' => 'thread_only' },
  163. \&foo);
  164. # Get thread's context
  165. my $wantarray = $thr->wantarray();
  166. # Check thread's state
  167. if ($thr->is_running()) {
  168. sleep(1);
  169. }
  170. if ($thr->is_joinable()) {
  171. $thr->join();
  172. }
  173. # Send a signal to a thread
  174. $thr->kill('SIGUSR1');
  175. # Exit a thread
  176. threads->exit();
  177. =head1 DESCRIPTION
  178. Since Perl 5.8, thread programming has been available using a model called
  179. I<interpreter threads> which provides a new Perl interpreter for each
  180. thread, and, by default, results in no data or state information being shared
  181. between threads.
  182. (Prior to Perl 5.8, I<5005threads> was available through the C<Thread.pm> API.
  183. This threading model has been deprecated, and was removed as of Perl 5.10.0.)
  184. As just mentioned, all variables are, by default, thread local. To use shared
  185. variables, you need to also load L<threads::shared>:
  186. use threads;
  187. use threads::shared;
  188. When loading L<threads::shared>, you must C<use threads> before you
  189. C<use threads::shared>. (C<threads> will emit a warning if you do it the
  190. other way around.)
  191. It is strongly recommended that you enable threads via C<use threads> as early
  192. as possible in your script.
  193. If needed, scripts can be written so as to run on both threaded and
  194. non-threaded Perls:
  195. my $can_use_threads = eval 'use threads; 1';
  196. if ($can_use_threads) {
  197. # Do processing using threads
  198. ...
  199. } else {
  200. # Do it without using threads
  201. ...
  202. }
  203. =over
  204. =item $thr = threads->create(FUNCTION, ARGS)
  205. This will create a new thread that will begin execution with the specified
  206. entry point function, and give it the I<ARGS> list as parameters. It will
  207. return the corresponding threads object, or C<undef> if thread creation failed.
  208. I<FUNCTION> may either be the name of a function, an anonymous subroutine, or
  209. a code ref.
  210. my $thr = threads->create('func_name', ...);
  211. # or
  212. my $thr = threads->create(sub { ... }, ...);
  213. # or
  214. my $thr = threads->create(\&func, ...);
  215. The C<-E<gt>new()> method is an alias for C<-E<gt>create()>.
  216. =item $thr->join()
  217. This will wait for the corresponding thread to complete its execution. When
  218. the thread finishes, C<-E<gt>join()> will return the return value(s) of the
  219. entry point function.
  220. The context (void, scalar or list) for the return value(s) for C<-E<gt>join()>
  221. is determined at the time of thread creation.
  222. # Create thread in list context (implicit)
  223. my ($thr1) = threads->create(sub {
  224. my @results = qw(a b c);
  225. return (@results);
  226. });
  227. # or (explicit)
  228. my $thr1 = threads->create({'context' => 'list'},
  229. sub {
  230. my @results = qw(a b c);
  231. return (@results);
  232. });
  233. # Retrieve list results from thread
  234. my @res1 = $thr1->join();
  235. # Create thread in scalar context (implicit)
  236. my $thr2 = threads->create(sub {
  237. my $result = 42;
  238. return ($result);
  239. });
  240. # Retrieve scalar result from thread
  241. my $res2 = $thr2->join();
  242. # Create a thread in void context (explicit)
  243. my $thr3 = threads->create({'void' => 1},
  244. sub { print("Hello, world\n"); });
  245. # Join the thread in void context (i.e., no return value)
  246. $thr3->join();
  247. See L</"THREAD CONTEXT"> for more details.
  248. If the program exits without all threads having either been joined or
  249. detached, then a warning will be issued.
  250. Calling C<-E<gt>join()> or C<-E<gt>detach()> on an already joined thread will
  251. cause an error to be thrown.
  252. =item $thr->detach()
  253. Makes the thread unjoinable, and causes any eventual return value to be
  254. discarded. When the program exits, any detached threads that are still
  255. running are silently terminated.
  256. If the program exits without all threads having either been joined or
  257. detached, then a warning will be issued.
  258. Calling C<-E<gt>join()> or C<-E<gt>detach()> on an already detached thread
  259. will cause an error to be thrown.
  260. =item threads->detach()
  261. Class method that allows a thread to detach itself.
  262. =item threads->self()
  263. Class method that allows a thread to obtain its own I<threads> object.
  264. =item $thr->tid()
  265. Returns the ID of the thread. Thread IDs are unique integers with the main
  266. thread in a program being 0, and incrementing by 1 for every thread created.
  267. =item threads->tid()
  268. Class method that allows a thread to obtain its own ID.
  269. =item "$thr"
  270. If you add the C<stringify> import option to your C<use threads> declaration,
  271. then using a threads object in a string or a string context (e.g., as a hash
  272. key) will cause its ID to be used as the value:
  273. use threads qw(stringify);
  274. my $thr = threads->create(...);
  275. print("Thread $thr started...\n"); # Prints out: Thread 1 started...
  276. =item threads->object($tid)
  277. This will return the I<threads> object for the I<active> thread associated
  278. with the specified thread ID. If C<$tid> is the value for the current thread,
  279. then this call works the same as C<-E<gt>self()>. Otherwise, returns C<undef>
  280. if there is no thread associated with the TID, if the thread is joined or
  281. detached, if no TID is specified or if the specified TID is undef.
  282. =item threads->yield()
  283. This is a suggestion to the OS to let this thread yield CPU time to other
  284. threads. What actually happens is highly dependent upon the underlying
  285. thread implementation.
  286. You may do C<use threads qw(yield)>, and then just use C<yield()> in your
  287. code.
  288. =item threads->list()
  289. =item threads->list(threads::all)
  290. =item threads->list(threads::running)
  291. =item threads->list(threads::joinable)
  292. With no arguments (or using C<threads::all>) and in a list context, returns a
  293. list of all non-joined, non-detached I<threads> objects. In a scalar context,
  294. returns a count of the same.
  295. With a I<true> argument (using C<threads::running>), returns a list of all
  296. non-joined, non-detached I<threads> objects that are still running.
  297. With a I<false> argument (using C<threads::joinable>), returns a list of all
  298. non-joined, non-detached I<threads> objects that have finished running (i.e.,
  299. for which C<-E<gt>join()> will not I<block>).
  300. =item $thr1->equal($thr2)
  301. Tests if two threads objects are the same thread or not. This is overloaded
  302. to the more natural forms:
  303. if ($thr1 == $thr2) {
  304. print("Threads are the same\n");
  305. }
  306. # or
  307. if ($thr1 != $thr2) {
  308. print("Threads differ\n");
  309. }
  310. (Thread comparison is based on thread IDs.)
  311. =item async BLOCK;
  312. C<async> creates a thread to execute the block immediately following
  313. it. This block is treated as an anonymous subroutine, and so must have a
  314. semicolon after the closing brace. Like C<threads-E<gt>create()>, C<async>
  315. returns a I<threads> object.
  316. =item $thr->error()
  317. Threads are executed in an C<eval> context. This method will return C<undef>
  318. if the thread terminates I<normally>. Otherwise, it returns the value of
  319. C<$@> associated with the thread's execution status in its C<eval> context.
  320. =item $thr->_handle()
  321. This I<private> method returns a pointer (i.e., the memory location expressed
  322. as an unsigned integer) to the internal thread structure associated with a
  323. threads object. For Win32, this is a pointer to the C<HANDLE> value returned
  324. by C<CreateThread> (i.e., C<HANDLE *>); for other platforms, it is a pointer
  325. to the C<pthread_t> structure used in the C<pthread_create> call (i.e.,
  326. C<pthread_t *>).
  327. This method is of no use for general Perl threads programming. Its intent is
  328. to provide other (XS-based) thread modules with the capability to access, and
  329. possibly manipulate, the underlying thread structure associated with a Perl
  330. thread.
  331. =item threads->_handle()
  332. Class method that allows a thread to obtain its own I<handle>.
  333. =back
  334. =head1 EXITING A THREAD
  335. The usual method for terminating a thread is to
  336. L<return()|perlfunc/"return EXPR"> from the entry point function with the
  337. appropriate return value(s).
  338. =over
  339. =item threads->exit()
  340. If needed, a thread can be exited at any time by calling
  341. C<threads-E<gt>exit()>. This will cause the thread to return C<undef> in a
  342. scalar context, or the empty list in a list context.
  343. When called from the I<main> thread, this behaves the same as C<exit(0)>.
  344. =item threads->exit(status)
  345. When called from a thread, this behaves like C<threads-E<gt>exit()> (i.e., the
  346. exit status code is ignored).
  347. When called from the I<main> thread, this behaves the same as C<exit(status)>.
  348. =item die()
  349. Calling C<die()> in a thread indicates an abnormal exit for the thread. Any
  350. C<$SIG{__DIE__}> handler in the thread will be called first, and then the
  351. thread will exit with a warning message that will contain any arguments passed
  352. in the C<die()> call.
  353. =item exit(status)
  354. Calling L<exit()|perlfunc/"exit EXPR"> inside a thread causes the whole
  355. application to terminate. Because of this, the use of C<exit()> inside
  356. threaded code, or in modules that might be used in threaded applications, is
  357. strongly discouraged.
  358. If C<exit()> really is needed, then consider using the following:
  359. threads->exit() if threads->can('exit'); # Thread friendly
  360. exit(status);
  361. =item use threads 'exit' => 'threads_only'
  362. This globally overrides the default behavior of calling C<exit()> inside a
  363. thread, and effectively causes such calls to behave the same as
  364. C<threads-E<gt>exit()>. In other words, with this setting, calling C<exit()>
  365. causes only the thread to terminate.
  366. Because of its global effect, this setting should not be used inside modules
  367. or the like.
  368. The I<main> thread is unaffected by this setting.
  369. =item threads->create({'exit' => 'thread_only'}, ...)
  370. This overrides the default behavior of C<exit()> inside the newly created
  371. thread only.
  372. =item $thr->set_thread_exit_only(boolean)
  373. This can be used to change the I<exit thread only> behavior for a thread after
  374. it has been created. With a I<true> argument, C<exit()> will cause only the
  375. thread to exit. With a I<false> argument, C<exit()> will terminate the
  376. application.
  377. The I<main> thread is unaffected by this call.
  378. =item threads->set_thread_exit_only(boolean)
  379. Class method for use inside a thread to change its own behavior for C<exit()>.
  380. The I<main> thread is unaffected by this call.
  381. =back
  382. =head1 THREAD STATE
  383. The following boolean methods are useful in determining the I<state> of a
  384. thread.
  385. =over
  386. =item $thr->is_running()
  387. Returns true if a thread is still running (i.e., if its entry point function
  388. has not yet finished or exited).
  389. =item $thr->is_joinable()
  390. Returns true if the thread has finished running, is not detached and has not
  391. yet been joined. In other words, the thread is ready to be joined, and a call
  392. to C<$thr-E<gt>join()> will not I<block>.
  393. =item $thr->is_detached()
  394. Returns true if the thread has been detached.
  395. =item threads->is_detached()
  396. Class method that allows a thread to determine whether or not it is detached.
  397. =back
  398. =head1 THREAD CONTEXT
  399. As with subroutines, the type of value returned from a thread's entry point
  400. function may be determined by the thread's I<context>: list, scalar or void.
  401. The thread's context is determined at thread creation. This is necessary so
  402. that the context is available to the entry point function via
  403. L<wantarray()|perlfunc/"wantarray">. The thread may then specify a value of
  404. the appropriate type to be returned from C<-E<gt>join()>.
  405. =head2 Explicit context
  406. Because thread creation and thread joining may occur in different contexts, it
  407. may be desirable to state the context explicitly to the thread's entry point
  408. function. This may be done by calling C<-E<gt>create()> with a hash reference
  409. as the first argument:
  410. my $thr = threads->create({'context' => 'list'}, \&foo);
  411. ...
  412. my @results = $thr->join();
  413. In the above, the threads object is returned to the parent thread in scalar
  414. context, and the thread's entry point function C<foo> will be called in list
  415. (array) context such that the parent thread can receive a list (array) from
  416. the C<-E<gt>join()> call. (C<'array'> is synonymous with C<'list'>.)
  417. Similarly, if you need the threads object, but your thread will not be
  418. returning a value (i.e., I<void> context), you would do the following:
  419. my $thr = threads->create({'context' => 'void'}, \&foo);
  420. ...
  421. $thr->join();
  422. The context type may also be used as the I<key> in the hash reference followed
  423. by a I<true> value:
  424. threads->create({'scalar' => 1}, \&foo);
  425. ...
  426. my ($thr) = threads->list();
  427. my $result = $thr->join();
  428. =head2 Implicit context
  429. If not explicitly stated, the thread's context is implied from the context
  430. of the C<-E<gt>create()> call:
  431. # Create thread in list context
  432. my ($thr) = threads->create(...);
  433. # Create thread in scalar context
  434. my $thr = threads->create(...);
  435. # Create thread in void context
  436. threads->create(...);
  437. =head2 $thr->wantarray()
  438. This returns the thread's context in the same manner as
  439. L<wantarray()|perlfunc/"wantarray">.
  440. =head2 threads->wantarray()
  441. Class method to return the current thread's context. This returns the same
  442. value as running L<wantarray()|perlfunc/"wantarray"> inside the current
  443. thread's entry point function.
  444. =head1 THREAD STACK SIZE
  445. The default per-thread stack size for different platforms varies
  446. significantly, and is almost always far more than is needed for most
  447. applications. On Win32, Perl's makefile explicitly sets the default stack to
  448. 16 MB; on most other platforms, the system default is used, which again may be
  449. much larger than is needed.
  450. By tuning the stack size to more accurately reflect your application's needs,
  451. you may significantly reduce your application's memory usage, and increase the
  452. number of simultaneously running threads.
  453. Note that on Windows, address space allocation granularity is 64 KB,
  454. therefore, setting the stack smaller than that on Win32 Perl will not save any
  455. more memory.
  456. =over
  457. =item threads->get_stack_size();
  458. Returns the current default per-thread stack size. The default is zero, which
  459. means the system default stack size is currently in use.
  460. =item $size = $thr->get_stack_size();
  461. Returns the stack size for a particular thread. A return value of zero
  462. indicates the system default stack size was used for the thread.
  463. =item $old_size = threads->set_stack_size($new_size);
  464. Sets a new default per-thread stack size, and returns the previous setting.
  465. Some platforms have a minimum thread stack size. Trying to set the stack size
  466. below this value will result in a warning, and the minimum stack size will be
  467. used.
  468. Some Linux platforms have a maximum stack size. Setting too large of a stack
  469. size will cause thread creation to fail.
  470. If needed, C<$new_size> will be rounded up to the next multiple of the memory
  471. page size (usually 4096 or 8192).
  472. Threads created after the stack size is set will then either call
  473. C<pthread_attr_setstacksize()> I<(for pthreads platforms)>, or supply the
  474. stack size to C<CreateThread()> I<(for Win32 Perl)>.
  475. (Obviously, this call does not affect any currently extant threads.)
  476. =item use threads ('stack_size' => VALUE);
  477. This sets the default per-thread stack size at the start of the application.
  478. =item $ENV{'PERL5_ITHREADS_STACK_SIZE'}
  479. The default per-thread stack size may be set at the start of the application
  480. through the use of the environment variable C<PERL5_ITHREADS_STACK_SIZE>:
  481. PERL5_ITHREADS_STACK_SIZE=1048576
  482. export PERL5_ITHREADS_STACK_SIZE
  483. perl -e'use threads; print(threads->get_stack_size(), "\n")'
  484. This value overrides any C<stack_size> parameter given to C<use threads>. Its
  485. primary purpose is to permit setting the per-thread stack size for legacy
  486. threaded applications.
  487. =item threads->create({'stack_size' => VALUE}, FUNCTION, ARGS)
  488. To specify a particular stack size for any individual thread, call
  489. C<-E<gt>create()> with a hash reference as the first argument:
  490. my $thr = threads->create({'stack_size' => 32*4096}, \&foo, @args);
  491. =item $thr2 = $thr1->create(FUNCTION, ARGS)
  492. This creates a new thread (C<$thr2>) that inherits the stack size from an
  493. existing thread (C<$thr1>). This is shorthand for the following:
  494. my $stack_size = $thr1->get_stack_size();
  495. my $thr2 = threads->create({'stack_size' => $stack_size}, FUNCTION, ARGS);
  496. =back
  497. =head1 THREAD SIGNALLING
  498. When safe signals is in effect (the default behavior - see L</"Unsafe signals">
  499. for more details), then signals may be sent and acted upon by individual
  500. threads.
  501. =over 4
  502. =item $thr->kill('SIG...');
  503. Sends the specified signal to the thread. Signal names and (positive) signal
  504. numbers are the same as those supported by
  505. L<kill()|perlfunc/"kill SIGNAL, LIST">. For example, 'SIGTERM', 'TERM' and
  506. (depending on the OS) 15 are all valid arguments to C<-E<gt>kill()>.
  507. Returns the thread object to allow for method chaining:
  508. $thr->kill('SIG...')->join();
  509. =back
  510. Signal handlers need to be set up in the threads for the signals they are
  511. expected to act upon. Here's an example for I<cancelling> a thread:
  512. use threads;
  513. sub thr_func
  514. {
  515. # Thread 'cancellation' signal handler
  516. $SIG{'KILL'} = sub { threads->exit(); };
  517. ...
  518. }
  519. # Create a thread
  520. my $thr = threads->create('thr_func');
  521. ...
  522. # Signal the thread to terminate, and then detach
  523. # it so that it will get cleaned up automatically
  524. $thr->kill('KILL')->detach();
  525. Here's another simplistic example that illustrates the use of thread
  526. signalling in conjunction with a semaphore to provide rudimentary I<suspend>
  527. and I<resume> capabilities:
  528. use threads;
  529. use Thread::Semaphore;
  530. sub thr_func
  531. {
  532. my $sema = shift;
  533. # Thread 'suspend/resume' signal handler
  534. $SIG{'STOP'} = sub {
  535. $sema->down(); # Thread suspended
  536. $sema->up(); # Thread resumes
  537. };
  538. ...
  539. }
  540. # Create a semaphore and pass it to a thread
  541. my $sema = Thread::Semaphore->new();
  542. my $thr = threads->create('thr_func', $sema);
  543. # Suspend the thread
  544. $sema->down();
  545. $thr->kill('STOP');
  546. ...
  547. # Allow the thread to continue
  548. $sema->up();
  549. CAVEAT: The thread signalling capability provided by this module does not
  550. actually send signals via the OS. It I<emulates> signals at the Perl-level
  551. such that signal handlers are called in the appropriate thread. For example,
  552. sending C<$thr-E<gt>kill('STOP')> does not actually suspend a thread (or the
  553. whole process), but does cause a C<$SIG{'STOP'}> handler to be called in that
  554. thread (as illustrated above).
  555. As such, signals that would normally not be appropriate to use in the
  556. C<kill()> command (e.g., C<kill('KILL', $$)>) are okay to use with the
  557. C<-E<gt>kill()> method (again, as illustrated above).
  558. Correspondingly, sending a signal to a thread does not disrupt the operation
  559. the thread is currently working on: The signal will be acted upon after the
  560. current operation has completed. For instance, if the thread is I<stuck> on
  561. an I/O call, sending it a signal will not cause the I/O call to be interrupted
  562. such that the signal is acted up immediately.
  563. Sending a signal to a terminated/finished thread is ignored.
  564. =head1 WARNINGS
  565. =over 4
  566. =item Perl exited with active threads:
  567. If the program exits without all threads having either been joined or
  568. detached, then this warning will be issued.
  569. NOTE: If the I<main> thread exits, then this warning cannot be suppressed
  570. using C<no warnings 'threads';> as suggested below.
  571. =item Thread creation failed: pthread_create returned #
  572. See the appropriate I<man> page for C<pthread_create> to determine the actual
  573. cause for the failure.
  574. =item Thread # terminated abnormally: ...
  575. A thread terminated in some manner other than just returning from its entry
  576. point function, or by using C<threads-E<gt>exit()>. For example, the thread
  577. may have terminated because of an error, or by using C<die>.
  578. =item Using minimum thread stack size of #
  579. Some platforms have a minimum thread stack size. Trying to set the stack size
  580. below this value will result in the above warning, and the stack size will be
  581. set to the minimum.
  582. =item Thread creation failed: pthread_attr_setstacksize(I<SIZE>) returned 22
  583. The specified I<SIZE> exceeds the system's maximum stack size. Use a smaller
  584. value for the stack size.
  585. =back
  586. If needed, thread warnings can be suppressed by using:
  587. no warnings 'threads';
  588. in the appropriate scope.
  589. =head1 ERRORS
  590. =over 4
  591. =item This Perl not built to support threads
  592. The particular copy of Perl that you're trying to use was not built using the
  593. C<useithreads> configuration option.
  594. Having threads support requires all of Perl and all of the XS modules in the
  595. Perl installation to be rebuilt; it is not just a question of adding the
  596. L<threads> module (i.e., threaded and non-threaded Perls are binary
  597. incompatible).
  598. =item Cannot change stack size of an existing thread
  599. The stack size of currently extant threads cannot be changed, therefore, the
  600. following results in the above error:
  601. $thr->set_stack_size($size);
  602. =item Cannot signal threads without safe signals
  603. Safe signals must be in effect to use the C<-E<gt>kill()> signalling method.
  604. See L</"Unsafe signals"> for more details.
  605. =item Unrecognized signal name: ...
  606. The particular copy of Perl that you're trying to use does not support the
  607. specified signal being used in a C<-E<gt>kill()> call.
  608. =back
  609. =head1 BUGS AND LIMITATIONS
  610. Before you consider posting a bug report, please consult, and possibly post a
  611. message to the discussion forum to see if what you've encountered is a known
  612. problem.
  613. =over
  614. =item Thread-safe modules
  615. See L<perlmod/"Making your module threadsafe"> when creating modules that may
  616. be used in threaded applications, especially if those modules use non-Perl
  617. data, or XS code.
  618. =item Using non-thread-safe modules
  619. Unfortunately, you may encounter Perl modules that are not I<thread-safe>.
  620. For example, they may crash the Perl interpreter during execution, or may dump
  621. core on termination. Depending on the module and the requirements of your
  622. application, it may be possible to work around such difficulties.
  623. If the module will only be used inside a thread, you can try loading the
  624. module from inside the thread entry point function using C<require> (and
  625. C<import> if needed):
  626. sub thr_func
  627. {
  628. require Unsafe::Module
  629. # Unsafe::Module->import(...);
  630. ....
  631. }
  632. If the module is needed inside the I<main> thread, try modifying your
  633. application so that the module is loaded (again using C<require> and
  634. C<-E<gt>import()>) after any threads are started, and in such a way that no
  635. other threads are started afterwards.
  636. If the above does not work, or is not adequate for your application, then file
  637. a bug report on L<http://rt.cpan.org/Public/> against the problematic module.
  638. =item Memory consumption
  639. On most systems, frequent and continual creation and destruction of threads
  640. can lead to ever-increasing growth in the memory footprint of the Perl
  641. interpreter. While it is simple to just launch threads and then
  642. C<-E<gt>join()> or C<-E<gt>detach()> them, for long-lived applications, it is
  643. better to maintain a pool of threads, and to reuse them for the work needed,
  644. using L<queues|Thread::Queue> to notify threads of pending work. The CPAN
  645. distribution of this module contains a simple example
  646. (F<examples/pool_reuse.pl>) illustrating the creation, use and monitoring of a
  647. pool of I<reusable> threads.
  648. =item Current working directory
  649. On all platforms except MSWin32, the setting for the current working directory
  650. is shared among all threads such that changing it in one thread (e.g., using
  651. C<chdir()>) will affect all the threads in the application.
  652. On MSWin32, each thread maintains its own the current working directory
  653. setting.
  654. =item Environment variables
  655. Currently, on all platforms except MSWin32, all I<system> calls (e.g., using
  656. C<system()> or back-ticks) made from threads use the environment variable
  657. settings from the I<main> thread. In other words, changes made to C<%ENV> in
  658. a thread will not be visible in I<system> calls made by that thread.
  659. To work around this, set environment variables as part of the I<system> call.
  660. For example:
  661. my $msg = 'hello';
  662. system("FOO=$msg; echo \$FOO"); # Outputs 'hello' to STDOUT
  663. On MSWin32, each thread maintains its own set of environment variables.
  664. =item Catching signals
  665. Signals are I<caught> by the main thread (thread ID = 0) of a script.
  666. Therefore, setting up signal handlers in threads for purposes other than
  667. L</"THREAD SIGNALLING"> as documented above will not accomplish what is
  668. intended.
  669. This is especially true if trying to catch C<SIGALRM> in a thread. To handle
  670. alarms in threads, set up a signal handler in the main thread, and then use
  671. L</"THREAD SIGNALLING"> to relay the signal to the thread:
  672. # Create thread with a task that may time out
  673. my $thr = threads->create(sub {
  674. threads->yield();
  675. eval {
  676. $SIG{ALRM} = sub { die("Timeout\n"); };
  677. alarm(10);
  678. ... # Do work here
  679. alarm(0);
  680. };
  681. if ($@ =~ /Timeout/) {
  682. warn("Task in thread timed out\n");
  683. }
  684. };
  685. # Set signal handler to relay SIGALRM to thread
  686. $SIG{ALRM} = sub { $thr->kill('ALRM') };
  687. ... # Main thread continues working
  688. =item Parent-child threads
  689. On some platforms, it might not be possible to destroy I<parent> threads while
  690. there are still existing I<child> threads.
  691. =item Creating threads inside special blocks
  692. Creating threads inside C<BEGIN>, C<CHECK> or C<INIT> blocks should not be
  693. relied upon. Depending on the Perl version and the application code, results
  694. may range from success, to (apparently harmless) warnings of leaked scalar, or
  695. all the way up to crashing of the Perl interpreter.
  696. =item Unsafe signals
  697. Since Perl 5.8.0, signals have been made safer in Perl by postponing their
  698. handling until the interpreter is in a I<safe> state. See
  699. L<perl58delta/"Safe Signals"> and L<perlipc/"Deferred Signals (Safe Signals)">
  700. for more details.
  701. Safe signals is the default behavior, and the old, immediate, unsafe
  702. signalling behavior is only in effect in the following situations:
  703. =over 4
  704. =item * Perl has been built with C<PERL_OLD_SIGNALS> (see C<perl -V>).
  705. =item * The environment variable C<PERL_SIGNALS> is set to C<unsafe>
  706. (see L<perlrun/"PERL_SIGNALS">).
  707. =item * The module L<Perl::Unsafe::Signals> is used.
  708. =back
  709. If unsafe signals is in effect, then signal handling is not thread-safe, and
  710. the C<-E<gt>kill()> signalling method cannot be used.
  711. =item Returning closures from threads
  712. Returning closures from threads should not be relied upon. Depending on the
  713. Perl version and the application code, results may range from success, to
  714. (apparently harmless) warnings of leaked scalar, or all the way up to crashing
  715. of the Perl interpreter.
  716. =item Returning objects from threads
  717. Returning objects from threads does not work. Depending on the classes
  718. involved, you may be able to work around this by returning a serialized
  719. version of the object (e.g., using L<Data::Dumper> or L<Storable>), and then
  720. reconstituting it in the joining thread. If you're using Perl 5.10.0 or
  721. later, and if the class supports L<shared objects|threads::shared/"OBJECTS">,
  722. you can pass them via L<shared queues|Thread::Queue>.
  723. =item END blocks in threads
  724. It is possible to add L<END blocks|perlmod/"BEGIN, UNITCHECK, CHECK, INIT and
  725. END"> to threads by using L<require|perlfunc/"require VERSION"> or
  726. L<eval|perlfunc/"eval EXPR"> with the appropriate code. These C<END> blocks
  727. will then be executed when the thread's interpreter is destroyed (i.e., either
  728. during a C<-E<gt>join()> call, or at program termination).
  729. However, calling any L<threads> methods in such an C<END> block will most
  730. likely I<fail> (e.g., the application may hang, or generate an error) due to
  731. mutexes that are needed to control functionality within the L<threads> module.
  732. For this reason, the use of C<END> blocks in threads is B<strongly>
  733. discouraged.
  734. =item Open directory handles
  735. In perl 5.14 and higher, on systems other than Windows that do
  736. not support the C<fchdir> C function, directory handles (see
  737. L<opendir|perlfunc/"opendir DIRHANDLE,EXPR">) will not be copied to new
  738. threads. You can use the C<d_fchdir> variable in L<Config.pm|Config> to
  739. determine whether your system supports it.
  740. In prior perl versions, spawning threads with open directory handles would
  741. crash the interpreter.
  742. L<[perl #75154]|http://rt.perl.org/rt3/Public/Bug/Display.html?id=75154>
  743. =item Perl Bugs and the CPAN Version of L<threads>
  744. Support for threads extends beyond the code in this module (i.e.,
  745. F<threads.pm> and F<threads.xs>), and into the Perl interpreter itself. Older
  746. versions of Perl contain bugs that may manifest themselves despite using the
  747. latest version of L<threads> from CPAN. There is no workaround for this other
  748. than upgrading to the latest version of Perl.
  749. Even with the latest version of Perl, it is known that certain constructs
  750. with threads may result in warning messages concerning leaked scalars or
  751. unreferenced scalars. However, such warnings are harmless, and may safely be
  752. ignored.
  753. You can search for L<threads> related bug reports at
  754. L<http://rt.cpan.org/Public/>. If needed submit any new bugs, problems,
  755. patches, etc. to: L<http://rt.cpan.org/Public/Dist/Display.html?Name=threads>
  756. =back
  757. =head1 REQUIREMENTS
  758. Perl 5.8.0 or later
  759. =head1 SEE ALSO
  760. L<threads> Discussion Forum on CPAN:
  761. L<http://www.cpanforum.com/dist/threads>
  762. L<threads::shared>, L<perlthrtut>
  763. L<http://www.perl.com/pub/a/2002/06/11/threads.html> and
  764. L<http://www.perl.com/pub/a/2002/09/04/threads.html>
  765. Perl threads mailing list:
  766. L<http://lists.perl.org/list/ithreads.html>
  767. Stack size discussion:
  768. L<http://www.perlmonks.org/?node_id=532956>
  769. =head1 AUTHOR
  770. Artur Bergman E<lt>sky AT crucially DOT netE<gt>
  771. CPAN version produced by Jerry D. Hedden <jdhedden AT cpan DOT org>
  772. =head1 LICENSE
  773. threads is released under the same license as Perl.
  774. =head1 ACKNOWLEDGEMENTS
  775. Richard Soderberg E<lt>perl AT crystalflame DOT netE<gt> -
  776. Helping me out tons, trying to find reasons for races and other weird bugs!
  777. Simon Cozens E<lt>simon AT brecon DOT co DOT ukE<gt> -
  778. Being there to answer zillions of annoying questions
  779. Rocco Caputo E<lt>troc AT netrus DOT netE<gt>
  780. Vipul Ved Prakash E<lt>mail AT vipul DOT netE<gt> -
  781. Helping with debugging
  782. Dean Arnold E<lt>darnold AT presicient DOT comE<gt> -
  783. Stack size API
  784. =cut