Initial commit of OpenSPARC T2 architecture model.
[OpenSPARC-T2-SAM] / sam-t2 / devtools / v8plus / man / man1 / perlthrtut.1
CommitLineData
920dae64
AT
1.\" Automatically generated by Pod::Man v1.37, Pod::Parser v1.32
2.\"
3.\" Standard preamble:
4.\" ========================================================================
5.de Sh \" Subsection heading
6.br
7.if t .Sp
8.ne 5
9.PP
10\fB\\$1\fR
11.PP
12..
13.de Sp \" Vertical space (when we can't use .PP)
14.if t .sp .5v
15.if n .sp
16..
17.de Vb \" Begin verbatim text
18.ft CW
19.nf
20.ne \\$1
21..
22.de Ve \" End verbatim text
23.ft R
24.fi
25..
26.\" Set up some character translations and predefined strings. \*(-- will
27.\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left
28.\" double quote, and \*(R" will give a right double quote. | will give a
29.\" real vertical bar. \*(C+ will give a nicer C++. Capital omega is used to
30.\" do unbreakable dashes and therefore won't be available. \*(C` and \*(C'
31.\" expand to `' in nroff, nothing in troff, for use with C<>.
32.tr \(*W-|\(bv\*(Tr
33.ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p'
34.ie n \{\
35. ds -- \(*W-
36. ds PI pi
37. if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch
38. if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch
39. ds L" ""
40. ds R" ""
41. ds C` ""
42. ds C' ""
43'br\}
44.el\{\
45. ds -- \|\(em\|
46. ds PI \(*p
47. ds L" ``
48. ds R" ''
49'br\}
50.\"
51.\" If the F register is turned on, we'll generate index entries on stderr for
52.\" titles (.TH), headers (.SH), subsections (.Sh), items (.Ip), and index
53.\" entries marked with X<> in POD. Of course, you'll have to process the
54.\" output yourself in some meaningful fashion.
55.if \nF \{\
56. de IX
57. tm Index:\\$1\t\\n%\t"\\$2"
58..
59. nr % 0
60. rr F
61.\}
62.\"
63.\" For nroff, turn off justification. Always turn off hyphenation; it makes
64.\" way too many mistakes in technical documents.
65.hy 0
66.if n .na
67.\"
68.\" Accent mark definitions (@(#)ms.acc 1.5 88/02/08 SMI; from UCB 4.2).
69.\" Fear. Run. Save yourself. No user-serviceable parts.
70. \" fudge factors for nroff and troff
71.if n \{\
72. ds #H 0
73. ds #V .8m
74. ds #F .3m
75. ds #[ \f1
76. ds #] \fP
77.\}
78.if t \{\
79. ds #H ((1u-(\\\\n(.fu%2u))*.13m)
80. ds #V .6m
81. ds #F 0
82. ds #[ \&
83. ds #] \&
84.\}
85. \" simple accents for nroff and troff
86.if n \{\
87. ds ' \&
88. ds ` \&
89. ds ^ \&
90. ds , \&
91. ds ~ ~
92. ds /
93.\}
94.if t \{\
95. ds ' \\k:\h'-(\\n(.wu*8/10-\*(#H)'\'\h"|\\n:u"
96. ds ` \\k:\h'-(\\n(.wu*8/10-\*(#H)'\`\h'|\\n:u'
97. ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'^\h'|\\n:u'
98. ds , \\k:\h'-(\\n(.wu*8/10)',\h'|\\n:u'
99. ds ~ \\k:\h'-(\\n(.wu-\*(#H-.1m)'~\h'|\\n:u'
100. ds / \\k:\h'-(\\n(.wu*8/10-\*(#H)'\z\(sl\h'|\\n:u'
101.\}
102. \" troff and (daisy-wheel) nroff accents
103.ds : \\k:\h'-(\\n(.wu*8/10-\*(#H+.1m+\*(#F)'\v'-\*(#V'\z.\h'.2m+\*(#F'.\h'|\\n:u'\v'\*(#V'
104.ds 8 \h'\*(#H'\(*b\h'-\*(#H'
105.ds o \\k:\h'-(\\n(.wu+\w'\(de'u-\*(#H)/2u'\v'-.3n'\*(#[\z\(de\v'.3n'\h'|\\n:u'\*(#]
106.ds d- \h'\*(#H'\(pd\h'-\w'~'u'\v'-.25m'\f2\(hy\fP\v'.25m'\h'-\*(#H'
107.ds D- D\\k:\h'-\w'D'u'\v'-.11m'\z\(hy\v'.11m'\h'|\\n:u'
108.ds th \*(#[\v'.3m'\s+1I\s-1\v'-.3m'\h'-(\w'I'u*2/3)'\s-1o\s+1\*(#]
109.ds Th \*(#[\s+2I\s-2\h'-\w'I'u*3/5'\v'-.3m'o\v'.3m'\*(#]
110.ds ae a\h'-(\w'a'u*4/10)'e
111.ds Ae A\h'-(\w'A'u*4/10)'E
112. \" corrections for vroff
113.if v .ds ~ \\k:\h'-(\\n(.wu*9/10-\*(#H)'\s-2\u~\d\s+2\h'|\\n:u'
114.if v .ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'\v'-.4m'^\v'.4m'\h'|\\n:u'
115. \" for low resolution devices (crt and lpr)
116.if \n(.H>23 .if \n(.V>19 \
117\{\
118. ds : e
119. ds 8 ss
120. ds o a
121. ds d- d\h'-1'\(ga
122. ds D- D\h'-1'\(hy
123. ds th \o'bp'
124. ds Th \o'LP'
125. ds ae ae
126. ds Ae AE
127.\}
128.rm #[ #] #H #V #F C
129.\" ========================================================================
130.\"
131.IX Title "PERLTHRTUT 1"
132.TH PERLTHRTUT 1 "2006-01-07" "perl v5.8.8" "Perl Programmers Reference Guide"
133.SH "NAME"
134perlthrtut \- tutorial on threads in Perl
135.SH "DESCRIPTION"
136.IX Header "DESCRIPTION"
137\&\fB\s-1NOTE\s0\fR: this tutorial describes the new Perl threading flavour
138introduced in Perl 5.6.0 called interpreter threads, or \fBithreads\fR
139for short. In this model each thread runs in its own Perl interpreter,
140and any data sharing between threads must be explicit.
141.PP
142There is another older Perl threading flavour called the 5.005 model,
143unsurprisingly for 5.005 versions of Perl. The old model is known to
144have problems, deprecated, and will probably be removed around release
1455.10. You are strongly encouraged to migrate any existing 5.005
146threads code to the new model as soon as possible.
147.PP
148You can see which (or neither) threading flavour you have by
149running \f(CW\*(C`perl \-V\*(C'\fR and looking at the \f(CW\*(C`Platform\*(C'\fR section.
150If you have \f(CW\*(C`useithreads=define\*(C'\fR you have ithreads, if you
151have \f(CW\*(C`use5005threads=define\*(C'\fR you have 5.005 threads.
152If you have neither, you don't have any thread support built in.
153If you have both, you are in trouble.
154.PP
155The user-level interface to the 5.005 threads was via the Threads
156class, while ithreads uses the threads class. Note the change in case.
157.SH "Status"
158.IX Header "Status"
159The ithreads code has been available since Perl 5.6.0, and is considered
160stable. The user-level interface to ithreads (the threads classes)
161appeared in the 5.8.0 release, and as of this time is considered stable
162although it should be treated with caution as with all new features.
163.SH "What Is A Thread Anyway?"
164.IX Header "What Is A Thread Anyway?"
165A thread is a flow of control through a program with a single
166execution point.
167.PP
168Sounds an awful lot like a process, doesn't it? Well, it should.
169Threads are one of the pieces of a process. Every process has at least
170one thread and, up until now, every process running Perl had only one
171thread. With 5.8, though, you can create extra threads. We're going
172to show you how, when, and why.
173.SH "Threaded Program Models"
174.IX Header "Threaded Program Models"
175There are three basic ways that you can structure a threaded
176program. Which model you choose depends on what you need your program
177to do. For many non-trivial threaded programs you'll need to choose
178different models for different pieces of your program.
179.Sh "Boss/Worker"
180.IX Subsection "Boss/Worker"
181The boss/worker model usually has one \*(L"boss\*(R" thread and one or more
182\&\*(L"worker\*(R" threads. The boss thread gathers or generates tasks that need
183to be done, then parcels those tasks out to the appropriate worker
184thread.
185.PP
186This model is common in \s-1GUI\s0 and server programs, where a main thread
187waits for some event and then passes that event to the appropriate
188worker threads for processing. Once the event has been passed on, the
189boss thread goes back to waiting for another event.
190.PP
191The boss thread does relatively little work. While tasks aren't
192necessarily performed faster than with any other method, it tends to
193have the best user-response times.
194.Sh "Work Crew"
195.IX Subsection "Work Crew"
196In the work crew model, several threads are created that do
197essentially the same thing to different pieces of data. It closely
198mirrors classical parallel processing and vector processors, where a
199large array of processors do the exact same thing to many pieces of
200data.
201.PP
202This model is particularly useful if the system running the program
203will distribute multiple threads across different processors. It can
204also be useful in ray tracing or rendering engines, where the
205individual threads can pass on interim results to give the user visual
206feedback.
207.Sh "Pipeline"
208.IX Subsection "Pipeline"
209The pipeline model divides up a task into a series of steps, and
210passes the results of one step on to the thread processing the
211next. Each thread does one thing to each piece of data and passes the
212results to the next thread in line.
213.PP
214This model makes the most sense if you have multiple processors so two
215or more threads will be executing in parallel, though it can often
216make sense in other contexts as well. It tends to keep the individual
217tasks small and simple, as well as allowing some parts of the pipeline
218to block (on I/O or system calls, for example) while other parts keep
219going. If you're running different parts of the pipeline on different
220processors you may also take advantage of the caches on each
221processor.
222.PP
223This model is also handy for a form of recursive programming where,
224rather than having a subroutine call itself, it instead creates
225another thread. Prime and Fibonacci generators both map well to this
226form of the pipeline model. (A version of a prime number generator is
227presented later on.)
228.SH "What kind of threads are Perl threads?"
229.IX Header "What kind of threads are Perl threads?"
230If you have experience with other thread implementations, you might
231find that things aren't quite what you expect. It's very important to
232remember when dealing with Perl threads that Perl Threads Are Not X
233Threads, for all values of X. They aren't \s-1POSIX\s0 threads, or
234DecThreads, or Java's Green threads, or Win32 threads. There are
235similarities, and the broad concepts are the same, but if you start
236looking for implementation details you're going to be either
237disappointed or confused. Possibly both.
238.PP
239This is not to say that Perl threads are completely different from
240everything that's ever come before\*(--they're not. Perl's threading
241model owes a lot to other thread models, especially \s-1POSIX\s0. Just as
242Perl is not C, though, Perl threads are not \s-1POSIX\s0 threads. So if you
243find yourself looking for mutexes, or thread priorities, it's time to
244step back a bit and think about what you want to do and how Perl can
245do it.
246.PP
247However it is important to remember that Perl threads cannot magically
248do things unless your operating systems threads allows it. So if your
249system blocks the entire process on \fIsleep()\fR, Perl usually will as well.
250.PP
251Perl Threads Are Different.
252.SH "Thread-Safe Modules"
253.IX Header "Thread-Safe Modules"
254The addition of threads has changed Perl's internals
255substantially. There are implications for people who write
256modules with \s-1XS\s0 code or external libraries. However, since perl data is
257not shared among threads by default, Perl modules stand a high chance of
258being thread-safe or can be made thread-safe easily. Modules that are not
259tagged as thread-safe should be tested or code reviewed before being used
260in production code.
261.PP
262Not all modules that you might use are thread\-safe, and you should
263always assume a module is unsafe unless the documentation says
264otherwise. This includes modules that are distributed as part of the
265core. Threads are a new feature, and even some of the standard
266modules aren't thread\-safe.
267.PP
268Even if a module is thread\-safe, it doesn't mean that the module is optimized
269to work well with threads. A module could possibly be rewritten to utilize
270the new features in threaded Perl to increase performance in a threaded
271environment.
272.PP
273If you're using a module that's not thread-safe for some reason, you
274can protect yourself by using it from one, and only one thread at all.
275If you need multiple threads to access such a module, you can use semaphores and
276lots of programming discipline to control access to it. Semaphores
277are covered in \*(L"Basic semaphores\*(R".
278.PP
279See also \*(L"Thread\-Safety of System Libraries\*(R".
280.SH "Thread Basics"
281.IX Header "Thread Basics"
282The core threads module provides the basic functions you need to write
283threaded programs. In the following sections we'll cover the basics,
284showing you what you need to do to create a threaded program. After
285that, we'll go over some of the features of the threads module that
286make threaded programming easier.
287.Sh "Basic Thread Support"
288.IX Subsection "Basic Thread Support"
289Thread support is a Perl compile-time option \- it's something that's
290turned on or off when Perl is built at your site, rather than when
291your programs are compiled. If your Perl wasn't compiled with thread
292support enabled, then any attempt to use threads will fail.
293.PP
294Your programs can use the Config module to check whether threads are
295enabled. If your program can't run without them, you can say something
296like:
297.PP
298.Vb 1
299\& $Config{useithreads} or die "Recompile Perl with threads to run this program.";
300.Ve
301.PP
302A possibly-threaded program using a possibly-threaded module might
303have code like this:
304.PP
305.Vb 2
306\& use Config;
307\& use MyMod;
308.Ve
309.PP
310.Vb 10
311\& BEGIN {
312\& if ($Config{useithreads}) {
313\& # We have threads
314\& require MyMod_threaded;
315\& import MyMod_threaded;
316\& } else {
317\& require MyMod_unthreaded;
318\& import MyMod_unthreaded;
319\& }
320\& }
321.Ve
322.PP
323Since code that runs both with and without threads is usually pretty
324messy, it's best to isolate the thread-specific code in its own
325module. In our example above, that's what MyMod_threaded is, and it's
326only imported if we're running on a threaded Perl.
327.Sh "A Note about the Examples"
328.IX Subsection "A Note about the Examples"
329Although thread support is considered to be stable, there are still a number
330of quirks that may startle you when you try out any of the examples below.
331In a real situation, care should be taken that all threads are finished
332executing before the program exits. That care has \fBnot\fR been taken in these
333examples in the interest of simplicity. Running these examples \*(L"as is\*(R" will
334produce error messages, usually caused by the fact that there are still
335threads running when the program exits. You should not be alarmed by this.
336Future versions of Perl may fix this problem.
337.Sh "Creating Threads"
338.IX Subsection "Creating Threads"
339The threads package provides the tools you need to create new
340threads. Like any other module, you need to tell Perl that you want to use
341it; \f(CW\*(C`use threads\*(C'\fR imports all the pieces you need to create basic
342threads.
343.PP
344The simplest, most straightforward way to create a thread is with \fInew()\fR:
345.PP
346.Vb 1
347\& use threads;
348.Ve
349.PP
350.Vb 1
351\& $thr = threads->new(\e&sub1);
352.Ve
353.PP
354.Vb 3
355\& sub sub1 {
356\& print "In the thread\en";
357\& }
358.Ve
359.PP
360The \fInew()\fR method takes a reference to a subroutine and creates a new
361thread, which starts executing in the referenced subroutine. Control
362then passes both to the subroutine and the caller.
363.PP
364If you need to, your program can pass parameters to the subroutine as
365part of the thread startup. Just include the list of parameters as
366part of the \f(CW\*(C`threads::new\*(C'\fR call, like this:
367.PP
368.Vb 1
369\& use threads;
370.Ve
371.PP
372.Vb 4
373\& $Param3 = "foo";
374\& $thr = threads->new(\e&sub1, "Param 1", "Param 2", $Param3);
375\& $thr = threads->new(\e&sub1, @ParamList);
376\& $thr = threads->new(\e&sub1, qw(Param1 Param2 Param3));
377.Ve
378.PP
379.Vb 5
380\& sub sub1 {
381\& my @InboundParameters = @_;
382\& print "In the thread\en";
383\& print "got parameters >", join("<>", @InboundParameters), "<\en";
384\& }
385.Ve
386.PP
387The last example illustrates another feature of threads. You can spawn
388off several threads using the same subroutine. Each thread executes
389the same subroutine, but in a separate thread with a separate
390environment and potentially separate arguments.
391.PP
392\&\f(CW\*(C`create()\*(C'\fR is a synonym for \f(CW\*(C`new()\*(C'\fR.
393.Sh "Waiting For A Thread To Exit"
394.IX Subsection "Waiting For A Thread To Exit"
395Since threads are also subroutines, they can return values. To wait
396for a thread to exit and extract any values it might return, you can
397use the \fIjoin()\fR method:
398.PP
399.Vb 1
400\& use threads;
401.Ve
402.PP
403.Vb 1
404\& $thr = threads->new(\e&sub1);
405.Ve
406.PP
407.Vb 2
408\& @ReturnData = $thr->join;
409\& print "Thread returned @ReturnData";
410.Ve
411.PP
412.Vb 1
413\& sub sub1 { return "Fifty-six", "foo", 2; }
414.Ve
415.PP
416In the example above, the \fIjoin()\fR method returns as soon as the thread
417ends. In addition to waiting for a thread to finish and gathering up
418any values that the thread might have returned, \fIjoin()\fR also performs
419any \s-1OS\s0 cleanup necessary for the thread. That cleanup might be
420important, especially for long-running programs that spawn lots of
421threads. If you don't want the return values and don't want to wait
422for the thread to finish, you should call the \fIdetach()\fR method
423instead, as described next.
424.Sh "Ignoring A Thread"
425.IX Subsection "Ignoring A Thread"
426\&\fIjoin()\fR does three things: it waits for a thread to exit, cleans up
427after it, and returns any data the thread may have produced. But what
428if you're not interested in the thread's return values, and you don't
429really care when the thread finishes? All you want is for the thread
430to get cleaned up after when it's done.
431.PP
432In this case, you use the \fIdetach()\fR method. Once a thread is detached,
433it'll run until it's finished, then Perl will clean up after it
434automatically.
435.PP
436.Vb 1
437\& use threads;
438.Ve
439.PP
440.Vb 1
441\& $thr = threads->new(\e&sub1); # Spawn the thread
442.Ve
443.PP
444.Vb 1
445\& $thr->detach; # Now we officially don't care any more
446.Ve
447.PP
448.Vb 8
449\& sub sub1 {
450\& $a = 0;
451\& while (1) {
452\& $a++;
453\& print "\e$a is $a\en";
454\& sleep 1;
455\& }
456\& }
457.Ve
458.PP
459Once a thread is detached, it may not be joined, and any return data
460that it might have produced (if it was done and waiting for a join) is
461lost.
462.SH "Threads And Data"
463.IX Header "Threads And Data"
464Now that we've covered the basics of threads, it's time for our next
465topic: data. Threading introduces a couple of complications to data
466access that non-threaded programs never need to worry about.
467.Sh "Shared And Unshared Data"
468.IX Subsection "Shared And Unshared Data"
469The biggest difference between Perl ithreads and the old 5.005 style
470threading, or for that matter, to most other threading systems out there,
471is that by default, no data is shared. When a new perl thread is created,
472all the data associated with the current thread is copied to the new
473thread, and is subsequently private to that new thread!
474This is similar in feel to what happens when a \s-1UNIX\s0 process forks,
475except that in this case, the data is just copied to a different part of
476memory within the same process rather than a real fork taking place.
477.PP
478To make use of threading however, one usually wants the threads to share
479at least some data between themselves. This is done with the
480threads::shared module and the \f(CW\*(C` : shared\*(C'\fR attribute:
481.PP
482.Vb 2
483\& use threads;
484\& use threads::shared;
485.Ve
486.PP
487.Vb 3
488\& my $foo : shared = 1;
489\& my $bar = 1;
490\& threads->new(sub { $foo++; $bar++ })->join;
491.Ve
492.PP
493.Vb 2
494\& print "$foo\en"; #prints 2 since $foo is shared
495\& print "$bar\en"; #prints 1 since $bar is not shared
496.Ve
497.PP
498In the case of a shared array, all the array's elements are shared, and for
499a shared hash, all the keys and values are shared. This places
500restrictions on what may be assigned to shared array and hash elements: only
501simple values or references to shared variables are allowed \- this is
502so that a private variable can't accidentally become shared. A bad
503assignment will cause the thread to die. For example:
504.PP
505.Vb 2
506\& use threads;
507\& use threads::shared;
508.Ve
509.PP
510.Vb 3
511\& my $var = 1;
512\& my $svar : shared = 2;
513\& my %hash : shared;
514.Ve
515.PP
516.Vb 1
517\& ... create some threads ...
518.Ve
519.PP
520.Vb 6
521\& $hash{a} = 1; # all threads see exists($hash{a}) and $hash{a} == 1
522\& $hash{a} = $var # okay - copy-by-value: same effect as previous
523\& $hash{a} = $svar # okay - copy-by-value: same effect as previous
524\& $hash{a} = \e$svar # okay - a reference to a shared variable
525\& $hash{a} = \e$var # This will die
526\& delete $hash{a} # okay - all threads will see !exists($hash{a})
527.Ve
528.PP
529Note that a shared variable guarantees that if two or more threads try to
530modify it at the same time, the internal state of the variable will not
531become corrupted. However, there are no guarantees beyond this, as
532explained in the next section.
533.Sh "Thread Pitfalls: Races"
534.IX Subsection "Thread Pitfalls: Races"
535While threads bring a new set of useful tools, they also bring a
536number of pitfalls. One pitfall is the race condition:
537.PP
538.Vb 2
539\& use threads;
540\& use threads::shared;
541.Ve
542.PP
543.Vb 3
544\& my $a : shared = 1;
545\& $thr1 = threads->new(\e&sub1);
546\& $thr2 = threads->new(\e&sub2);
547.Ve
548.PP
549.Vb 3
550\& $thr1->join;
551\& $thr2->join;
552\& print "$a\en";
553.Ve
554.PP
555.Vb 2
556\& sub sub1 { my $foo = $a; $a = $foo + 1; }
557\& sub sub2 { my $bar = $a; $a = $bar + 1; }
558.Ve
559.PP
560What do you think \f(CW$a\fR will be? The answer, unfortunately, is \*(L"it
561depends.\*(R" Both \fIsub1()\fR and \fIsub2()\fR access the global variable \f(CW$a\fR, once
562to read and once to write. Depending on factors ranging from your
563thread implementation's scheduling algorithm to the phase of the moon,
564\&\f(CW$a\fR can be 2 or 3.
565.PP
566Race conditions are caused by unsynchronized access to shared
567data. Without explicit synchronization, there's no way to be sure that
568nothing has happened to the shared data between the time you access it
569and the time you update it. Even this simple code fragment has the
570possibility of error:
571.PP
572.Vb 8
573\& use threads;
574\& my $a : shared = 2;
575\& my $b : shared;
576\& my $c : shared;
577\& my $thr1 = threads->create(sub { $b = $a; $a = $b + 1; });
578\& my $thr2 = threads->create(sub { $c = $a; $a = $c + 1; });
579\& $thr1->join;
580\& $thr2->join;
581.Ve
582.PP
583Two threads both access \f(CW$a\fR. Each thread can potentially be interrupted
584at any point, or be executed in any order. At the end, \f(CW$a\fR could be 3
585or 4, and both \f(CW$b\fR and \f(CW$c\fR could be 2 or 3.
586.PP
587Even \f(CW\*(C`$a += 5\*(C'\fR or \f(CW\*(C`$a++\*(C'\fR are not guaranteed to be atomic.
588.PP
589Whenever your program accesses data or resources that can be accessed
590by other threads, you must take steps to coordinate access or risk
591data inconsistency and race conditions. Note that Perl will protect its
592internals from your race conditions, but it won't protect you from you.
593.SH "Synchronization and control"
594.IX Header "Synchronization and control"
595Perl provides a number of mechanisms to coordinate the interactions
596between themselves and their data, to avoid race conditions and the like.
597Some of these are designed to resemble the common techniques used in thread
598libraries such as \f(CW\*(C`pthreads\*(C'\fR; others are Perl\-specific. Often, the
599standard techniques are clumsy and difficult to get right (such as
600condition waits). Where possible, it is usually easier to use Perlish
601techniques such as queues, which remove some of the hard work involved.
602.Sh "Controlling access: \fIlock()\fP"
603.IX Subsection "Controlling access: lock()"
604The \fIlock()\fR function takes a shared variable and puts a lock on it.
605No other thread may lock the variable until the variable is unlocked
606by the thread holding the lock. Unlocking happens automatically
607when the locking thread exits the outermost block that contains
608\&\f(CW\*(C`lock()\*(C'\fR function. Using \fIlock()\fR is straightforward: this example has
609several threads doing some calculations in parallel, and occasionally
610updating a running total:
611.PP
612.Vb 2
613\& use threads;
614\& use threads::shared;
615.Ve
616.PP
617.Vb 1
618\& my $total : shared = 0;
619.Ve
620.PP
621.Vb 11
622\& sub calc {
623\& for (;;) {
624\& my $result;
625\& # (... do some calculations and set $result ...)
626\& {
627\& lock($total); # block until we obtain the lock
628\& $total += $result;
629\& } # lock implicitly released at end of scope
630\& last if $result == 0;
631\& }
632\& }
633.Ve
634.PP
635.Vb 7
636\& my $thr1 = threads->new(\e&calc);
637\& my $thr2 = threads->new(\e&calc);
638\& my $thr3 = threads->new(\e&calc);
639\& $thr1->join;
640\& $thr2->join;
641\& $thr3->join;
642\& print "total=$total\en";
643.Ve
644.PP
645\&\fIlock()\fR blocks the thread until the variable being locked is
646available. When \fIlock()\fR returns, your thread can be sure that no other
647thread can lock that variable until the outermost block containing the
648lock exits.
649.PP
650It's important to note that locks don't prevent access to the variable
651in question, only lock attempts. This is in keeping with Perl's
652longstanding tradition of courteous programming, and the advisory file
653locking that \fIflock()\fR gives you.
654.PP
655You may lock arrays and hashes as well as scalars. Locking an array,
656though, will not block subsequent locks on array elements, just lock
657attempts on the array itself.
658.PP
659Locks are recursive, which means it's okay for a thread to
660lock a variable more than once. The lock will last until the outermost
661\&\fIlock()\fR on the variable goes out of scope. For example:
662.PP
663.Vb 2
664\& my $x : shared;
665\& doit();
666.Ve
667.PP
668.Vb 15
669\& sub doit {
670\& {
671\& {
672\& lock($x); # wait for lock
673\& lock($x); # NOOP - we already have the lock
674\& {
675\& lock($x); # NOOP
676\& {
677\& lock($x); # NOOP
678\& lockit_some_more();
679\& }
680\& }
681\& } # *** implicit unlock here ***
682\& }
683\& }
684.Ve
685.PP
686.Vb 3
687\& sub lockit_some_more {
688\& lock($x); # NOOP
689\& } # nothing happens here
690.Ve
691.PP
692Note that there is no \fIunlock()\fR function \- the only way to unlock a
693variable is to allow it to go out of scope.
694.PP
695A lock can either be used to guard the data contained within the variable
696being locked, or it can be used to guard something else, like a section
697of code. In this latter case, the variable in question does not hold any
698useful data, and exists only for the purpose of being locked. In this
699respect, the variable behaves like the mutexes and basic semaphores of
700traditional thread libraries.
701.Sh "A Thread Pitfall: Deadlocks"
702.IX Subsection "A Thread Pitfall: Deadlocks"
703Locks are a handy tool to synchronize access to data, and using them
704properly is the key to safe shared data. Unfortunately, locks aren't
705without their dangers, especially when multiple locks are involved.
706Consider the following code:
707.PP
708.Vb 1
709\& use threads;
710.Ve
711.PP
712.Vb 12
713\& my $a : shared = 4;
714\& my $b : shared = "foo";
715\& my $thr1 = threads->new(sub {
716\& lock($a);
717\& sleep 20;
718\& lock($b);
719\& });
720\& my $thr2 = threads->new(sub {
721\& lock($b);
722\& sleep 20;
723\& lock($a);
724\& });
725.Ve
726.PP
727This program will probably hang until you kill it. The only way it
728won't hang is if one of the two threads acquires both locks
729first. A guaranteed-to-hang version is more complicated, but the
730principle is the same.
731.PP
732The first thread will grab a lock on \f(CW$a\fR, then, after a pause during which
733the second thread has probably had time to do some work, try to grab a
734lock on \f(CW$b\fR. Meanwhile, the second thread grabs a lock on \f(CW$b\fR, then later
735tries to grab a lock on \f(CW$a\fR. The second lock attempt for both threads will
736block, each waiting for the other to release its lock.
737.PP
738This condition is called a deadlock, and it occurs whenever two or
739more threads are trying to get locks on resources that the others
740own. Each thread will block, waiting for the other to release a lock
741on a resource. That never happens, though, since the thread with the
742resource is itself waiting for a lock to be released.
743.PP
744There are a number of ways to handle this sort of problem. The best
745way is to always have all threads acquire locks in the exact same
746order. If, for example, you lock variables \f(CW$a\fR, \f(CW$b\fR, and \f(CW$c\fR, always lock
747\&\f(CW$a\fR before \f(CW$b\fR, and \f(CW$b\fR before \f(CW$c\fR. It's also best to hold on to locks for
748as short a period of time to minimize the risks of deadlock.
749.PP
750The other synchronization primitives described below can suffer from
751similar problems.
752.Sh "Queues: Passing Data Around"
753.IX Subsection "Queues: Passing Data Around"
754A queue is a special thread-safe object that lets you put data in one
755end and take it out the other without having to worry about
756synchronization issues. They're pretty straightforward, and look like
757this:
758.PP
759.Vb 2
760\& use threads;
761\& use Thread::Queue;
762.Ve
763.PP
764.Vb 6
765\& my $DataQueue = Thread::Queue->new;
766\& $thr = threads->new(sub {
767\& while ($DataElement = $DataQueue->dequeue) {
768\& print "Popped $DataElement off the queue\en";
769\& }
770\& });
771.Ve
772.PP
773.Vb 6
774\& $DataQueue->enqueue(12);
775\& $DataQueue->enqueue("A", "B", "C");
776\& $DataQueue->enqueue(\e$thr);
777\& sleep 10;
778\& $DataQueue->enqueue(undef);
779\& $thr->join;
780.Ve
781.PP
782You create the queue with \f(CW\*(C`new Thread::Queue\*(C'\fR. Then you can
783add lists of scalars onto the end with \fIenqueue()\fR, and pop scalars off
784the front of it with \fIdequeue()\fR. A queue has no fixed size, and can grow
785as needed to hold everything pushed on to it.
786.PP
787If a queue is empty, \fIdequeue()\fR blocks until another thread enqueues
788something. This makes queues ideal for event loops and other
789communications between threads.
790.Sh "Semaphores: Synchronizing Data Access"
791.IX Subsection "Semaphores: Synchronizing Data Access"
792Semaphores are a kind of generic locking mechanism. In their most basic
793form, they behave very much like lockable scalars, except that they
794can't hold data, and that they must be explicitly unlocked. In their
795advanced form, they act like a kind of counter, and can allow multiple
796threads to have the 'lock' at any one time.
797.Sh "Basic semaphores"
798.IX Subsection "Basic semaphores"
799Semaphores have two methods, \fIdown()\fR and \fIup()\fR: \fIdown()\fR decrements the resource
800count, while up increments it. Calls to \fIdown()\fR will block if the
801semaphore's current count would decrement below zero. This program
802gives a quick demonstration:
803.PP
804.Vb 2
805\& use threads;
806\& use Thread::Semaphore;
807.Ve
808.PP
809.Vb 2
810\& my $semaphore = new Thread::Semaphore;
811\& my $GlobalVariable : shared = 0;
812.Ve
813.PP
814.Vb 3
815\& $thr1 = new threads \e&sample_sub, 1;
816\& $thr2 = new threads \e&sample_sub, 2;
817\& $thr3 = new threads \e&sample_sub, 3;
818.Ve
819.PP
820.Vb 15
821\& sub sample_sub {
822\& my $SubNumber = shift @_;
823\& my $TryCount = 10;
824\& my $LocalCopy;
825\& sleep 1;
826\& while ($TryCount--) {
827\& $semaphore->down;
828\& $LocalCopy = $GlobalVariable;
829\& print "$TryCount tries left for sub $SubNumber (\e$GlobalVariable is $GlobalVariable)\en";
830\& sleep 2;
831\& $LocalCopy++;
832\& $GlobalVariable = $LocalCopy;
833\& $semaphore->up;
834\& }
835\& }
836.Ve
837.PP
838.Vb 3
839\& $thr1->join;
840\& $thr2->join;
841\& $thr3->join;
842.Ve
843.PP
844The three invocations of the subroutine all operate in sync. The
845semaphore, though, makes sure that only one thread is accessing the
846global variable at once.
847.Sh "Advanced Semaphores"
848.IX Subsection "Advanced Semaphores"
849By default, semaphores behave like locks, letting only one thread
850\&\fIdown()\fR them at a time. However, there are other uses for semaphores.
851.PP
852Each semaphore has a counter attached to it. By default, semaphores are
853created with the counter set to one, \fIdown()\fR decrements the counter by
854one, and \fIup()\fR increments by one. However, we can override any or all
855of these defaults simply by passing in different values:
856.PP
857.Vb 4
858\& use threads;
859\& use Thread::Semaphore;
860\& my $semaphore = Thread::Semaphore->new(5);
861\& # Creates a semaphore with the counter set to five
862.Ve
863.PP
864.Vb 2
865\& $thr1 = threads->new(\e&sub1);
866\& $thr2 = threads->new(\e&sub1);
867.Ve
868.PP
869.Vb 5
870\& sub sub1 {
871\& $semaphore->down(5); # Decrements the counter by five
872\& # Do stuff here
873\& $semaphore->up(5); # Increment the counter by five
874\& }
875.Ve
876.PP
877.Vb 2
878\& $thr1->detach;
879\& $thr2->detach;
880.Ve
881.PP
882If \fIdown()\fR attempts to decrement the counter below zero, it blocks until
883the counter is large enough. Note that while a semaphore can be created
884with a starting count of zero, any \fIup()\fR or \fIdown()\fR always changes the
885counter by at least one, and so \f(CW$semaphore\fR\->\fIdown\fR\|(0) is the same as
886\&\f(CW$semaphore\fR\->\fIdown\fR\|(1).
887.PP
888The question, of course, is why would you do something like this? Why
889create a semaphore with a starting count that's not one, or why
890decrement/increment it by more than one? The answer is resource
891availability. Many resources that you want to manage access for can be
892safely used by more than one thread at once.
893.PP
894For example, let's take a \s-1GUI\s0 driven program. It has a semaphore that
895it uses to synchronize access to the display, so only one thread is
896ever drawing at once. Handy, but of course you don't want any thread
897to start drawing until things are properly set up. In this case, you
898can create a semaphore with a counter set to zero, and up it when
899things are ready for drawing.
900.PP
901Semaphores with counters greater than one are also useful for
902establishing quotas. Say, for example, that you have a number of
903threads that can do I/O at once. You don't want all the threads
904reading or writing at once though, since that can potentially swamp
905your I/O channels, or deplete your process' quota of filehandles. You
906can use a semaphore initialized to the number of concurrent I/O
907requests (or open files) that you want at any one time, and have your
908threads quietly block and unblock themselves.
909.PP
910Larger increments or decrements are handy in those cases where a
911thread needs to check out or return a number of resources at once.
912.Sh "\fIcond_wait()\fP and \fIcond_signal()\fP"
913.IX Subsection "cond_wait() and cond_signal()"
914These two functions can be used in conjunction with locks to notify
915co-operating threads that a resource has become available. They are
916very similar in use to the functions found in \f(CW\*(C`pthreads\*(C'\fR. However
917for most purposes, queues are simpler to use and more intuitive. See
918threads::shared for more details.
919.Sh "Giving up control"
920.IX Subsection "Giving up control"
921There are times when you may find it useful to have a thread
922explicitly give up the \s-1CPU\s0 to another thread. You may be doing something
923processor-intensive and want to make sure that the user-interface thread
924gets called frequently. Regardless, there are times that you might want
925a thread to give up the processor.
926.PP
927Perl's threading package provides the \fIyield()\fR function that does
928this. \fIyield()\fR is pretty straightforward, and works like this:
929.PP
930.Vb 1
931\& use threads;
932.Ve
933.PP
934.Vb 8
935\& sub loop {
936\& my $thread = shift;
937\& my $foo = 50;
938\& while($foo--) { print "in thread $thread\en" }
939\& threads->yield;
940\& $foo = 50;
941\& while($foo--) { print "in thread $thread\en" }
942\& }
943.Ve
944.PP
945.Vb 3
946\& my $thread1 = threads->new(\e&loop, 'first');
947\& my $thread2 = threads->new(\e&loop, 'second');
948\& my $thread3 = threads->new(\e&loop, 'third');
949.Ve
950.PP
951It is important to remember that \fIyield()\fR is only a hint to give up the \s-1CPU\s0,
952it depends on your hardware, \s-1OS\s0 and threading libraries what actually happens.
953\&\fBOn many operating systems, \f(BIyield()\fB is a no\-op.\fR Therefore it is important
954to note that one should not build the scheduling of the threads around
955\&\fIyield()\fR calls. It might work on your platform but it won't work on another
956platform.
957.SH "General Thread Utility Routines"
958.IX Header "General Thread Utility Routines"
959We've covered the workhorse parts of Perl's threading package, and
960with these tools you should be well on your way to writing threaded
961code and packages. There are a few useful little pieces that didn't
962really fit in anyplace else.
963.Sh "What Thread Am I In?"
964.IX Subsection "What Thread Am I In?"
965The \f(CW\*(C`threads\->self\*(C'\fR class method provides your program with a way to
966get an object representing the thread it's currently in. You can use this
967object in the same way as the ones returned from thread creation.
968.Sh "Thread IDs"
969.IX Subsection "Thread IDs"
970\&\fItid()\fR is a thread object method that returns the thread \s-1ID\s0 of the
971thread the object represents. Thread IDs are integers, with the main
972thread in a program being 0. Currently Perl assigns a unique tid to
973every thread ever created in your program, assigning the first thread
974to be created a tid of 1, and increasing the tid by 1 for each new
975thread that's created.
976.Sh "Are These Threads The Same?"
977.IX Subsection "Are These Threads The Same?"
978The \fIequal()\fR method takes two thread objects and returns true
979if the objects represent the same thread, and false if they don't.
980.PP
981Thread objects also have an overloaded == comparison so that you can do
982comparison on them as you would with normal objects.
983.Sh "What Threads Are Running?"
984.IX Subsection "What Threads Are Running?"
985\&\f(CW\*(C`threads\->list\*(C'\fR returns a list of thread objects, one for each thread
986that's currently running and not detached. Handy for a number of things,
987including cleaning up at the end of your program:
988.PP
989.Vb 7
990\& # Loop through all the threads
991\& foreach $thr (threads->list) {
992\& # Don't join the main thread or ourselves
993\& if ($thr->tid && !threads::equal($thr, threads->self)) {
994\& $thr->join;
995\& }
996\& }
997.Ve
998.PP
999If some threads have not finished running when the main Perl thread
1000ends, Perl will warn you about it and die, since it is impossible for Perl
1001to clean up itself while other threads are running
1002.SH "A Complete Example"
1003.IX Header "A Complete Example"
1004Confused yet? It's time for an example program to show some of the
1005things we've covered. This program finds prime numbers using threads.
1006.PP
1007.Vb 34
1008\& 1 #!/usr/bin/perl -w
1009\& 2 # prime-pthread, courtesy of Tom Christiansen
1010\& 3
1011\& 4 use strict;
1012\& 5
1013\& 6 use threads;
1014\& 7 use Thread::Queue;
1015\& 8
1016\& 9 my $stream = new Thread::Queue;
1017\& 10 my $kid = new threads(\e&check_num, $stream, 2);
1018\& 11
1019\& 12 for my $i ( 3 .. 1000 ) {
1020\& 13 $stream->enqueue($i);
1021\& 14 }
1022\& 15
1023\& 16 $stream->enqueue(undef);
1024\& 17 $kid->join;
1025\& 18
1026\& 19 sub check_num {
1027\& 20 my ($upstream, $cur_prime) = @_;
1028\& 21 my $kid;
1029\& 22 my $downstream = new Thread::Queue;
1030\& 23 while (my $num = $upstream->dequeue) {
1031\& 24 next unless $num % $cur_prime;
1032\& 25 if ($kid) {
1033\& 26 $downstream->enqueue($num);
1034\& 27 } else {
1035\& 28 print "Found prime $num\en";
1036\& 29 $kid = new threads(\e&check_num, $downstream, $num);
1037\& 30 }
1038\& 31 }
1039\& 32 $downstream->enqueue(undef) if $kid;
1040\& 33 $kid->join if $kid;
1041\& 34 }
1042.Ve
1043.PP
1044This program uses the pipeline model to generate prime numbers. Each
1045thread in the pipeline has an input queue that feeds numbers to be
1046checked, a prime number that it's responsible for, and an output queue
1047into which it funnels numbers that have failed the check. If the thread
1048has a number that's failed its check and there's no child thread, then
1049the thread must have found a new prime number. In that case, a new
1050child thread is created for that prime and stuck on the end of the
1051pipeline.
1052.PP
1053This probably sounds a bit more confusing than it really is, so let's
1054go through this program piece by piece and see what it does. (For
1055those of you who might be trying to remember exactly what a prime
1056number is, it's a number that's only evenly divisible by itself and 1)
1057.PP
1058The bulk of the work is done by the \fIcheck_num()\fR subroutine, which
1059takes a reference to its input queue and a prime number that it's
1060responsible for. After pulling in the input queue and the prime that
1061the subroutine's checking (line 20), we create a new queue (line 22)
1062and reserve a scalar for the thread that we're likely to create later
1063(line 21).
1064.PP
1065The while loop from lines 23 to line 31 grabs a scalar off the input
1066queue and checks against the prime this thread is responsible
1067for. Line 24 checks to see if there's a remainder when we modulo the
1068number to be checked against our prime. If there is one, the number
1069must not be evenly divisible by our prime, so we need to either pass
1070it on to the next thread if we've created one (line 26) or create a
1071new thread if we haven't.
1072.PP
1073The new thread creation is line 29. We pass on to it a reference to
1074the queue we've created, and the prime number we've found.
1075.PP
1076Finally, once the loop terminates (because we got a 0 or undef in the
1077queue, which serves as a note to die), we pass on the notice to our
1078child and wait for it to exit if we've created a child (lines 32 and
107937).
1080.PP
1081Meanwhile, back in the main thread, we create a queue (line 9) and the
1082initial child thread (line 10), and pre-seed it with the first prime:
10832. Then we queue all the numbers from 3 to 1000 for checking (lines
108412\-14), then queue a die notice (line 16) and wait for the first child
1085thread to terminate (line 17). Because a child won't die until its
1086child has died, we know that we're done once we return from the join.
1087.PP
1088That's how it works. It's pretty simple; as with many Perl programs,
1089the explanation is much longer than the program.
1090.SH "Different implementations of threads"
1091.IX Header "Different implementations of threads"
1092Some background on thread implementations from the operating system
1093viewpoint. There are three basic categories of threads: user-mode threads,
1094kernel threads, and multiprocessor kernel threads.
1095.PP
1096User-mode threads are threads that live entirely within a program and
1097its libraries. In this model, the \s-1OS\s0 knows nothing about threads. As
1098far as it's concerned, your process is just a process.
1099.PP
1100This is the easiest way to implement threads, and the way most OSes
1101start. The big disadvantage is that, since the \s-1OS\s0 knows nothing about
1102threads, if one thread blocks they all do. Typical blocking activities
1103include most system calls, most I/O, and things like \fIsleep()\fR.
1104.PP
1105Kernel threads are the next step in thread evolution. The \s-1OS\s0 knows
1106about kernel threads, and makes allowances for them. The main
1107difference between a kernel thread and a user-mode thread is
1108blocking. With kernel threads, things that block a single thread don't
1109block other threads. This is not the case with user-mode threads,
1110where the kernel blocks at the process level and not the thread level.
1111.PP
1112This is a big step forward, and can give a threaded program quite a
1113performance boost over non-threaded programs. Threads that block
1114performing I/O, for example, won't block threads that are doing other
1115things. Each process still has only one thread running at once,
1116though, regardless of how many CPUs a system might have.
1117.PP
1118Since kernel threading can interrupt a thread at any time, they will
1119uncover some of the implicit locking assumptions you may make in your
1120program. For example, something as simple as \f(CW\*(C`$a = $a + 2\*(C'\fR can behave
1121unpredictably with kernel threads if \f(CW$a\fR is visible to other
1122threads, as another thread may have changed \f(CW$a\fR between the time it
1123was fetched on the right hand side and the time the new value is
1124stored.
1125.PP
1126Multiprocessor kernel threads are the final step in thread
1127support. With multiprocessor kernel threads on a machine with multiple
1128CPUs, the \s-1OS\s0 may schedule two or more threads to run simultaneously on
1129different CPUs.
1130.PP
1131This can give a serious performance boost to your threaded program,
1132since more than one thread will be executing at the same time. As a
1133tradeoff, though, any of those nagging synchronization issues that
1134might not have shown with basic kernel threads will appear with a
1135vengeance.
1136.PP
1137In addition to the different levels of \s-1OS\s0 involvement in threads,
1138different OSes (and different thread implementations for a particular
1139\&\s-1OS\s0) allocate \s-1CPU\s0 cycles to threads in different ways.
1140.PP
1141Cooperative multitasking systems have running threads give up control
1142if one of two things happen. If a thread calls a yield function, it
1143gives up control. It also gives up control if the thread does
1144something that would cause it to block, such as perform I/O. In a
1145cooperative multitasking implementation, one thread can starve all the
1146others for \s-1CPU\s0 time if it so chooses.
1147.PP
1148Preemptive multitasking systems interrupt threads at regular intervals
1149while the system decides which thread should run next. In a preemptive
1150multitasking system, one thread usually won't monopolize the \s-1CPU\s0.
1151.PP
1152On some systems, there can be cooperative and preemptive threads
1153running simultaneously. (Threads running with realtime priorities
1154often behave cooperatively, for example, while threads running at
1155normal priorities behave preemptively.)
1156.PP
1157Most modern operating systems support preemptive multitasking nowadays.
1158.SH "Performance considerations"
1159.IX Header "Performance considerations"
1160The main thing to bear in mind when comparing ithreads to other threading
1161models is the fact that for each new thread created, a complete copy of
1162all the variables and data of the parent thread has to be taken. Thus
1163thread creation can be quite expensive, both in terms of memory usage and
1164time spent in creation. The ideal way to reduce these costs is to have a
1165relatively short number of long-lived threads, all created fairly early
1166on \- before the base thread has accumulated too much data. Of course, this
1167may not always be possible, so compromises have to be made. However, after
1168a thread has been created, its performance and extra memory usage should
1169be little different than ordinary code.
1170.PP
1171Also note that under the current implementation, shared variables
1172use a little more memory and are a little slower than ordinary variables.
1173.SH "Process-scope Changes"
1174.IX Header "Process-scope Changes"
1175Note that while threads themselves are separate execution threads and
1176Perl data is thread-private unless explicitly shared, the threads can
1177affect process-scope state, affecting all the threads.
1178.PP
1179The most common example of this is changing the current working
1180directory using \fIchdir()\fR. One thread calls \fIchdir()\fR, and the working
1181directory of all the threads changes.
1182.PP
1183Even more drastic example of a process-scope change is \fIchroot()\fR:
1184the root directory of all the threads changes, and no thread can
1185undo it (as opposed to \fIchdir()\fR).
1186.PP
1187Further examples of process-scope changes include \fIumask()\fR and
1188changing uids/gids.
1189.PP
1190Thinking of mixing \fIfork()\fR and threads? Please lie down and wait
1191until the feeling passes. Be aware that the semantics of \fIfork()\fR vary
1192between platforms. For example, some \s-1UNIX\s0 systems copy all the current
1193threads into the child process, while others only copy the thread that
1194called \fIfork()\fR. You have been warned!
1195.PP
1196Similarly, mixing signals and threads should not be attempted.
1197Implementations are platform\-dependent, and even the \s-1POSIX\s0
1198semantics may not be what you expect (and Perl doesn't even
1199give you the full \s-1POSIX\s0 \s-1API\s0).
1200.SH "Thread-Safety of System Libraries"
1201.IX Header "Thread-Safety of System Libraries"
1202Whether various library calls are thread-safe is outside the control
1203of Perl. Calls often suffering from not being thread-safe include:
1204\&\fIlocaltime()\fR, \fIgmtime()\fR, get{gr,host,net,proto,serv,pw}*(), \fIreaddir()\fR,
1205\&\fIrand()\fR, and \fIsrand()\fR \*(-- in general, calls that depend on some global
1206external state.
1207.PP
1208If the system Perl is compiled in has thread-safe variants of such
1209calls, they will be used. Beyond that, Perl is at the mercy of
1210the thread-safety or \-unsafety of the calls. Please consult your
1211C library call documentation.
1212.PP
1213On some platforms the thread-safe library interfaces may fail if the
1214result buffer is too small (for example the user group databases may
1215be rather large, and the reentrant interfaces may have to carry around
1216a full snapshot of those databases). Perl will start with a small
1217buffer, but keep retrying and growing the result buffer
1218until the result fits. If this limitless growing sounds bad for
1219security or memory consumption reasons you can recompile Perl with
1220\&\s-1PERL_REENTRANT_MAXSIZE\s0 defined to the maximum number of bytes you will
1221allow.
1222.SH "Conclusion"
1223.IX Header "Conclusion"
1224A complete thread tutorial could fill a book (and has, many times),
1225but with what we've covered in this introduction, you should be well
1226on your way to becoming a threaded Perl expert.
1227.SH "Bibliography"
1228.IX Header "Bibliography"
1229