Debian Codegraph @

upstream/opensuse-tumbleweed/man1/perlthrtut.1

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