1PERLTHRTUT(1) Perl Programmers Reference Guide PERLTHRTUT(1)
2
3
4
6 perlthrtut - tutorial on threads in Perl
7
9 NOTE: this tutorial describes the new Perl threading flavour introduced
10 in Perl 5.6.0 called interpreter threads, or ithreads for short. In
11 this model each thread runs in its own Perl interpreter, and any data
12 sharing between threads must be explicit.
13
14 There is another older Perl threading flavour called the 5.005 model,
15 unsurprisingly for 5.005 versions of Perl. The old model is known to
16 have problems, deprecated, and will probably be removed around release
17 5.10. You are strongly encouraged to migrate any existing 5.005 threads
18 code to the new model as soon as possible.
19
20 You can see which (or neither) threading flavour you have by running
21 "perl -V" and looking at the "Platform" section. If you have "usei‐
22 threads=define" you have ithreads, if you have "use5005threads=define"
23 you have 5.005 threads. If you have neither, you don't have any thread
24 support built in. If you have both, you are in trouble.
25
26 The user-level interface to the 5.005 threads was via the Threads
27 class, while ithreads uses the threads class. Note the change in case.
28
30 The ithreads code has been available since Perl 5.6.0, and is consid‐
31 ered stable. The user-level interface to ithreads (the threads classes)
32 appeared in the 5.8.0 release, and as of this time is considered stable
33 although it should be treated with caution as with all new features.
34
36 A thread is a flow of control through a program with a single execution
37 point.
38
39 Sounds an awful lot like a process, doesn't it? Well, it should.
40 Threads are one of the pieces of a process. Every process has at least
41 one thread and, up until now, every process running Perl had only one
42 thread. With 5.8, though, you can create extra threads. We're going
43 to show you how, when, and why.
44
46 There are three basic ways that you can structure a threaded program.
47 Which model you choose depends on what you need your program to do.
48 For many non-trivial threaded programs you'll need to choose different
49 models for different pieces of your program.
50
51 Boss/Worker
52
53 The boss/worker model usually has one "boss" thread and one or more
54 "worker" threads. The boss thread gathers or generates tasks that need
55 to be done, then parcels those tasks out to the appropriate worker
56 thread.
57
58 This model is common in GUI and server programs, where a main thread
59 waits for some event and then passes that event to the appropriate
60 worker threads for processing. Once the event has been passed on, the
61 boss thread goes back to waiting for another event.
62
63 The boss thread does relatively little work. While tasks aren't neces‐
64 sarily performed faster than with any other method, it tends to have
65 the best user-response times.
66
67 Work Crew
68
69 In the work crew model, several threads are created that do essentially
70 the same thing to different pieces of data. It closely mirrors classi‐
71 cal parallel processing and vector processors, where a large array of
72 processors do the exact same thing to many pieces of data.
73
74 This model is particularly useful if the system running the program
75 will distribute multiple threads across different processors. It can
76 also be useful in ray tracing or rendering engines, where the individ‐
77 ual threads can pass on interim results to give the user visual feed‐
78 back.
79
80 Pipeline
81
82 The pipeline model divides up a task into a series of steps, and passes
83 the results of one step on to the thread processing the next. Each
84 thread does one thing to each piece of data and passes the results to
85 the next thread in line.
86
87 This model makes the most sense if you have multiple processors so two
88 or more threads will be executing in parallel, though it can often make
89 sense in other contexts as well. It tends to keep the individual tasks
90 small and simple, as well as allowing some parts of the pipeline to
91 block (on I/O or system calls, for example) while other parts keep
92 going. If you're running different parts of the pipeline on different
93 processors you may also take advantage of the caches on each processor.
94
95 This model is also handy for a form of recursive programming where,
96 rather than having a subroutine call itself, it instead creates another
97 thread. Prime and Fibonacci generators both map well to this form of
98 the pipeline model. (A version of a prime number generator is presented
99 later on.)
100
102 If you have experience with other thread implementations, you might
103 find that things aren't quite what you expect. It's very important to
104 remember when dealing with Perl threads that Perl Threads Are Not X
105 Threads, for all values of X. They aren't POSIX threads, or Dec‐
106 Threads, or Java's Green threads, or Win32 threads. There are similar‐
107 ities, and the broad concepts are the same, but if you start looking
108 for implementation details you're going to be either disappointed or
109 confused. Possibly both.
110
111 This is not to say that Perl threads are completely different from
112 everything that's ever come before--they're not. Perl's threading
113 model owes a lot to other thread models, especially POSIX. Just as
114 Perl is not C, though, Perl threads are not POSIX threads. So if you
115 find yourself looking for mutexes, or thread priorities, it's time to
116 step back a bit and think about what you want to do and how Perl can do
117 it.
118
119 However it is important to remember that Perl threads cannot magically
120 do things unless your operating systems threads allows it. So if your
121 system blocks the entire process on sleep(), Perl usually will as well.
122
123 Perl Threads Are Different.
124
126 The addition of threads has changed Perl's internals substantially.
127 There are implications for people who write modules with XS code or
128 external libraries. However, since perl data is not shared among
129 threads by default, Perl modules stand a high chance of being thread-
130 safe or can be made thread-safe easily. Modules that are not tagged as
131 thread-safe should be tested or code reviewed before being used in pro‐
132 duction code.
133
134 Not all modules that you might use are thread-safe, and you should
135 always assume a module is unsafe unless the documentation says other‐
136 wise. This includes modules that are distributed as part of the core.
137 Threads are a new feature, and even some of the standard modules aren't
138 thread-safe.
139
140 Even if a module is thread-safe, it doesn't mean that the module is
141 optimized to work well with threads. A module could possibly be rewrit‐
142 ten to utilize the new features in threaded Perl to increase perfor‐
143 mance in a threaded environment.
144
145 If you're using a module that's not thread-safe for some reason, you
146 can protect yourself by using it from one, and only one thread at all.
147 If you need multiple threads to access such a module, you can use sema‐
148 phores and lots of programming discipline to control access to it.
149 Semaphores are covered in "Basic semaphores".
150
151 See also "Thread-Safety of System Libraries".
152
154 The core threads module provides the basic functions you need to write
155 threaded programs. In the following sections we'll cover the basics,
156 showing you what you need to do to create a threaded program. After
157 that, we'll go over some of the features of the threads module that
158 make threaded programming easier.
159
160 Basic Thread Support
161
162 Thread support is a Perl compile-time option - it's something that's
163 turned on or off when Perl is built at your site, rather than when your
164 programs are compiled. If your Perl wasn't compiled with thread support
165 enabled, then any attempt to use threads will fail.
166
167 Your programs can use the Config module to check whether threads are
168 enabled. If your program can't run without them, you can say something
169 like:
170
171 $Config{useithreads} or die "Recompile Perl with threads to run this program.";
172
173 A possibly-threaded program using a possibly-threaded module might have
174 code like this:
175
176 use Config;
177 use MyMod;
178
179 BEGIN {
180 if ($Config{useithreads}) {
181 # We have threads
182 require MyMod_threaded;
183 import MyMod_threaded;
184 } else {
185 require MyMod_unthreaded;
186 import MyMod_unthreaded;
187 }
188 }
189
190 Since code that runs both with and without threads is usually pretty
191 messy, it's best to isolate the thread-specific code in its own module.
192 In our example above, that's what MyMod_threaded is, and it's only
193 imported if we're running on a threaded Perl.
194
195 A Note about the Examples
196
197 Although thread support is considered to be stable, there are still a
198 number of quirks that may startle you when you try out any of the exam‐
199 ples below. In a real situation, care should be taken that all threads
200 are finished executing before the program exits. That care has not
201 been taken in these examples in the interest of simplicity. Running
202 these examples "as is" will produce error messages, usually caused by
203 the fact that there are still threads running when the program exits.
204 You should not be alarmed by this. Future versions of Perl may fix
205 this problem.
206
207 Creating Threads
208
209 The threads package provides the tools you need to create new threads.
210 Like any other module, you need to tell Perl that you want to use it;
211 "use threads" imports all the pieces you need to create basic threads.
212
213 The simplest, most straightforward way to create a thread is with
214 new():
215
216 use threads;
217
218 $thr = threads->new(\&sub1);
219
220 sub sub1 {
221 print "In the thread\n";
222 }
223
224 The new() method takes a reference to a subroutine and creates a new
225 thread, which starts executing in the referenced subroutine. Control
226 then passes both to the subroutine and the caller.
227
228 If you need to, your program can pass parameters to the subroutine as
229 part of the thread startup. Just include the list of parameters as
230 part of the "threads::new" call, like this:
231
232 use threads;
233
234 $Param3 = "foo";
235 $thr = threads->new(\&sub1, "Param 1", "Param 2", $Param3);
236 $thr = threads->new(\&sub1, @ParamList);
237 $thr = threads->new(\&sub1, qw(Param1 Param2 Param3));
238
239 sub sub1 {
240 my @InboundParameters = @_;
241 print "In the thread\n";
242 print "got parameters >", join("<>", @InboundParameters), "<\n";
243 }
244
245 The last example illustrates another feature of threads. You can spawn
246 off several threads using the same subroutine. Each thread executes
247 the same subroutine, but in a separate thread with a separate environ‐
248 ment and potentially separate arguments.
249
250 "create()" is a synonym for "new()".
251
252 Waiting For A Thread To Exit
253
254 Since threads are also subroutines, they can return values. To wait
255 for a thread to exit and extract any values it might return, you can
256 use the join() method:
257
258 use threads;
259
260 $thr = threads->new(\&sub1);
261
262 @ReturnData = $thr->join;
263 print "Thread returned @ReturnData";
264
265 sub sub1 { return "Fifty-six", "foo", 2; }
266
267 In the example above, the join() method returns as soon as the thread
268 ends. In addition to waiting for a thread to finish and gathering up
269 any values that the thread might have returned, join() also performs
270 any OS cleanup necessary for the thread. That cleanup might be impor‐
271 tant, especially for long-running programs that spawn lots of threads.
272 If you don't want the return values and don't want to wait for the
273 thread to finish, you should call the detach() method instead, as
274 described next.
275
276 Ignoring A Thread
277
278 join() does three things: it waits for a thread to exit, cleans up
279 after it, and returns any data the thread may have produced. But what
280 if you're not interested in the thread's return values, and you don't
281 really care when the thread finishes? All you want is for the thread to
282 get cleaned up after when it's done.
283
284 In this case, you use the detach() method. Once a thread is detached,
285 it'll run until it's finished, then Perl will clean up after it auto‐
286 matically.
287
288 use threads;
289
290 $thr = threads->new(\&sub1); # Spawn the thread
291
292 $thr->detach; # Now we officially don't care any more
293
294 sub sub1 {
295 $a = 0;
296 while (1) {
297 $a++;
298 print "\$a is $a\n";
299 sleep 1;
300 }
301 }
302
303 Once a thread is detached, it may not be joined, and any return data
304 that it might have produced (if it was done and waiting for a join) is
305 lost.
306
308 Now that we've covered the basics of threads, it's time for our next
309 topic: data. Threading introduces a couple of complications to data
310 access that non-threaded programs never need to worry about.
311
312 Shared And Unshared Data
313
314 The biggest difference between Perl ithreads and the old 5.005 style
315 threading, or for that matter, to most other threading systems out
316 there, is that by default, no data is shared. When a new perl thread is
317 created, all the data associated with the current thread is copied to
318 the new thread, and is subsequently private to that new thread! This
319 is similar in feel to what happens when a UNIX process forks, except
320 that in this case, the data is just copied to a different part of mem‐
321 ory within the same process rather than a real fork taking place.
322
323 To make use of threading however, one usually wants the threads to
324 share at least some data between themselves. This is done with the
325 threads::shared module and the " : shared" attribute:
326
327 use threads;
328 use threads::shared;
329
330 my $foo : shared = 1;
331 my $bar = 1;
332 threads->new(sub { $foo++; $bar++ })->join;
333
334 print "$foo\n"; #prints 2 since $foo is shared
335 print "$bar\n"; #prints 1 since $bar is not shared
336
337 In the case of a shared array, all the array's elements are shared, and
338 for a shared hash, all the keys and values are shared. This places
339 restrictions on what may be assigned to shared array and hash elements:
340 only simple values or references to shared variables are allowed - this
341 is so that a private variable can't accidentally become shared. A bad
342 assignment will cause the thread to die. For example:
343
344 use threads;
345 use threads::shared;
346
347 my $var = 1;
348 my $svar : shared = 2;
349 my %hash : shared;
350
351 ... create some threads ...
352
353 $hash{a} = 1; # all threads see exists($hash{a}) and $hash{a} == 1
354 $hash{a} = $var # okay - copy-by-value: same effect as previous
355 $hash{a} = $svar # okay - copy-by-value: same effect as previous
356 $hash{a} = \$svar # okay - a reference to a shared variable
357 $hash{a} = \$var # This will die
358 delete $hash{a} # okay - all threads will see !exists($hash{a})
359
360 Note that a shared variable guarantees that if two or more threads try
361 to modify it at the same time, the internal state of the variable will
362 not become corrupted. However, there are no guarantees beyond this, as
363 explained in the next section.
364
365 Thread Pitfalls: Races
366
367 While threads bring a new set of useful tools, they also bring a number
368 of pitfalls. One pitfall is the race condition:
369
370 use threads;
371 use threads::shared;
372
373 my $a : shared = 1;
374 $thr1 = threads->new(\&sub1);
375 $thr2 = threads->new(\&sub2);
376
377 $thr1->join;
378 $thr2->join;
379 print "$a\n";
380
381 sub sub1 { my $foo = $a; $a = $foo + 1; }
382 sub sub2 { my $bar = $a; $a = $bar + 1; }
383
384 What do you think $a will be? The answer, unfortunately, is "it
385 depends." Both sub1() and sub2() access the global variable $a, once to
386 read and once to write. Depending on factors ranging from your thread
387 implementation's scheduling algorithm to the phase of the moon, $a can
388 be 2 or 3.
389
390 Race conditions are caused by unsynchronized access to shared data.
391 Without explicit synchronization, there's no way to be sure that noth‐
392 ing has happened to the shared data between the time you access it and
393 the time you update it. Even this simple code fragment has the possi‐
394 bility of error:
395
396 use threads;
397 my $a : shared = 2;
398 my $b : shared;
399 my $c : shared;
400 my $thr1 = threads->create(sub { $b = $a; $a = $b + 1; });
401 my $thr2 = threads->create(sub { $c = $a; $a = $c + 1; });
402 $thr1->join;
403 $thr2->join;
404
405 Two threads both access $a. Each thread can potentially be interrupted
406 at any point, or be executed in any order. At the end, $a could be 3
407 or 4, and both $b and $c could be 2 or 3.
408
409 Even "$a += 5" or "$a++" are not guaranteed to be atomic.
410
411 Whenever your program accesses data or resources that can be accessed
412 by other threads, you must take steps to coordinate access or risk data
413 inconsistency and race conditions. Note that Perl will protect its
414 internals from your race conditions, but it won't protect you from you.
415
417 Perl provides a number of mechanisms to coordinate the interactions
418 between themselves and their data, to avoid race conditions and the
419 like. Some of these are designed to resemble the common techniques
420 used in thread libraries such as "pthreads"; others are Perl-specific.
421 Often, the standard techniques are clumsy and difficult to get right
422 (such as condition waits). Where possible, it is usually easier to use
423 Perlish techniques such as queues, which remove some of the hard work
424 involved.
425
426 Controlling access: lock()
427
428 The lock() function takes a shared variable and puts a lock on it. No
429 other thread may lock the variable until the variable is unlocked by
430 the thread holding the lock. Unlocking happens automatically when the
431 locking thread exits the outermost block that contains "lock()" func‐
432 tion. Using lock() is straightforward: this example has several
433 threads doing some calculations in parallel, and occasionally updating
434 a running total:
435
436 use threads;
437 use threads::shared;
438
439 my $total : shared = 0;
440
441 sub calc {
442 for (;;) {
443 my $result;
444 # (... do some calculations and set $result ...)
445 {
446 lock($total); # block until we obtain the lock
447 $total += $result;
448 } # lock implicitly released at end of scope
449 last if $result == 0;
450 }
451 }
452
453 my $thr1 = threads->new(\&calc);
454 my $thr2 = threads->new(\&calc);
455 my $thr3 = threads->new(\&calc);
456 $thr1->join;
457 $thr2->join;
458 $thr3->join;
459 print "total=$total\n";
460
461 lock() blocks the thread until the variable being locked is available.
462 When lock() returns, your thread can be sure that no other thread can
463 lock that variable until the outermost block containing the lock exits.
464
465 It's important to note that locks don't prevent access to the variable
466 in question, only lock attempts. This is in keeping with Perl's long‐
467 standing tradition of courteous programming, and the advisory file
468 locking that flock() gives you.
469
470 You may lock arrays and hashes as well as scalars. Locking an array,
471 though, will not block subsequent locks on array elements, just lock
472 attempts on the array itself.
473
474 Locks are recursive, which means it's okay for a thread to lock a vari‐
475 able more than once. The lock will last until the outermost lock() on
476 the variable goes out of scope. For example:
477
478 my $x : shared;
479 doit();
480
481 sub doit {
482 {
483 {
484 lock($x); # wait for lock
485 lock($x); # NOOP - we already have the lock
486 {
487 lock($x); # NOOP
488 {
489 lock($x); # NOOP
490 lockit_some_more();
491 }
492 }
493 } # *** implicit unlock here ***
494 }
495 }
496
497 sub lockit_some_more {
498 lock($x); # NOOP
499 } # nothing happens here
500
501 Note that there is no unlock() function - the only way to unlock a
502 variable is to allow it to go out of scope.
503
504 A lock can either be used to guard the data contained within the vari‐
505 able being locked, or it can be used to guard something else, like a
506 section of code. In this latter case, the variable in question does not
507 hold any useful data, and exists only for the purpose of being locked.
508 In this respect, the variable behaves like the mutexes and basic sema‐
509 phores of traditional thread libraries.
510
511 A Thread Pitfall: Deadlocks
512
513 Locks are a handy tool to synchronize access to data, and using them
514 properly is the key to safe shared data. Unfortunately, locks aren't
515 without their dangers, especially when multiple locks are involved.
516 Consider the following code:
517
518 use threads;
519
520 my $a : shared = 4;
521 my $b : shared = "foo";
522 my $thr1 = threads->new(sub {
523 lock($a);
524 sleep 20;
525 lock($b);
526 });
527 my $thr2 = threads->new(sub {
528 lock($b);
529 sleep 20;
530 lock($a);
531 });
532
533 This program will probably hang until you kill it. The only way it
534 won't hang is if one of the two threads acquires both locks first. A
535 guaranteed-to-hang version is more complicated, but the principle is
536 the same.
537
538 The first thread will grab a lock on $a, then, after a pause during
539 which the second thread has probably had time to do some work, try to
540 grab a lock on $b. Meanwhile, the second thread grabs a lock on $b,
541 then later tries to grab a lock on $a. The second lock attempt for
542 both threads will block, each waiting for the other to release its
543 lock.
544
545 This condition is called a deadlock, and it occurs whenever two or more
546 threads are trying to get locks on resources that the others own. Each
547 thread will block, waiting for the other to release a lock on a
548 resource. That never happens, though, since the thread with the
549 resource is itself waiting for a lock to be released.
550
551 There are a number of ways to handle this sort of problem. The best
552 way is to always have all threads acquire locks in the exact same
553 order. If, for example, you lock variables $a, $b, and $c, always lock
554 $a before $b, and $b before $c. It's also best to hold on to locks for
555 as short a period of time to minimize the risks of deadlock.
556
557 The other synchronization primitives described below can suffer from
558 similar problems.
559
560 Queues: Passing Data Around
561
562 A queue is a special thread-safe object that lets you put data in one
563 end and take it out the other without having to worry about synchro‐
564 nization issues. They're pretty straightforward, and look like this:
565
566 use threads;
567 use Thread::Queue;
568
569 my $DataQueue = Thread::Queue->new;
570 $thr = threads->new(sub {
571 while ($DataElement = $DataQueue->dequeue) {
572 print "Popped $DataElement off the queue\n";
573 }
574 });
575
576 $DataQueue->enqueue(12);
577 $DataQueue->enqueue("A", "B", "C");
578 $DataQueue->enqueue(\$thr);
579 sleep 10;
580 $DataQueue->enqueue(undef);
581 $thr->join;
582
583 You create the queue with "new Thread::Queue". Then you can add lists
584 of scalars onto the end with enqueue(), and pop scalars off the front
585 of it with dequeue(). A queue has no fixed size, and can grow as
586 needed to hold everything pushed on to it.
587
588 If a queue is empty, dequeue() blocks until another thread enqueues
589 something. This makes queues ideal for event loops and other communi‐
590 cations between threads.
591
592 Semaphores: Synchronizing Data Access
593
594 Semaphores are a kind of generic locking mechanism. In their most basic
595 form, they behave very much like lockable scalars, except that they
596 can't hold data, and that they must be explicitly unlocked. In their
597 advanced form, they act like a kind of counter, and can allow multiple
598 threads to have the 'lock' at any one time.
599
600 Basic semaphores
601
602 Semaphores have two methods, down() and up(): down() decrements the
603 resource count, while up increments it. Calls to down() will block if
604 the semaphore's current count would decrement below zero. This program
605 gives a quick demonstration:
606
607 use threads;
608 use Thread::Semaphore;
609
610 my $semaphore = new Thread::Semaphore;
611 my $GlobalVariable : shared = 0;
612
613 $thr1 = new threads \&sample_sub, 1;
614 $thr2 = new threads \&sample_sub, 2;
615 $thr3 = new threads \&sample_sub, 3;
616
617 sub sample_sub {
618 my $SubNumber = shift @_;
619 my $TryCount = 10;
620 my $LocalCopy;
621 sleep 1;
622 while ($TryCount--) {
623 $semaphore->down;
624 $LocalCopy = $GlobalVariable;
625 print "$TryCount tries left for sub $SubNumber (\$GlobalVariable is $GlobalVariable)\n";
626 sleep 2;
627 $LocalCopy++;
628 $GlobalVariable = $LocalCopy;
629 $semaphore->up;
630 }
631 }
632
633 $thr1->join;
634 $thr2->join;
635 $thr3->join;
636
637 The three invocations of the subroutine all operate in sync. The sema‐
638 phore, though, makes sure that only one thread is accessing the global
639 variable at once.
640
641 Advanced Semaphores
642
643 By default, semaphores behave like locks, letting only one thread
644 down() them at a time. However, there are other uses for semaphores.
645
646 Each semaphore has a counter attached to it. By default, semaphores are
647 created with the counter set to one, down() decrements the counter by
648 one, and up() increments by one. However, we can override any or all of
649 these defaults simply by passing in different values:
650
651 use threads;
652 use Thread::Semaphore;
653 my $semaphore = Thread::Semaphore->new(5);
654 # Creates a semaphore with the counter set to five
655
656 $thr1 = threads->new(\&sub1);
657 $thr2 = threads->new(\&sub1);
658
659 sub sub1 {
660 $semaphore->down(5); # Decrements the counter by five
661 # Do stuff here
662 $semaphore->up(5); # Increment the counter by five
663 }
664
665 $thr1->detach;
666 $thr2->detach;
667
668 If down() attempts to decrement the counter below zero, it blocks until
669 the counter is large enough. Note that while a semaphore can be cre‐
670 ated with a starting count of zero, any up() or down() always changes
671 the counter by at least one, and so $semaphore->down(0) is the same as
672 $semaphore->down(1).
673
674 The question, of course, is why would you do something like this? Why
675 create a semaphore with a starting count that's not one, or why decre‐
676 ment/increment it by more than one? The answer is resource availabil‐
677 ity. Many resources that you want to manage access for can be safely
678 used by more than one thread at once.
679
680 For example, let's take a GUI driven program. It has a semaphore that
681 it uses to synchronize access to the display, so only one thread is
682 ever drawing at once. Handy, but of course you don't want any thread
683 to start drawing until things are properly set up. In this case, you
684 can create a semaphore with a counter set to zero, and up it when
685 things are ready for drawing.
686
687 Semaphores with counters greater than one are also useful for estab‐
688 lishing quotas. Say, for example, that you have a number of threads
689 that can do I/O at once. You don't want all the threads reading or
690 writing at once though, since that can potentially swamp your I/O chan‐
691 nels, or deplete your process' quota of filehandles. You can use a
692 semaphore initialized to the number of concurrent I/O requests (or open
693 files) that you want at any one time, and have your threads quietly
694 block and unblock themselves.
695
696 Larger increments or decrements are handy in those cases where a thread
697 needs to check out or return a number of resources at once.
698
699 cond_wait() and cond_signal()
700
701 These two functions can be used in conjunction with locks to notify co-
702 operating threads that a resource has become available. They are very
703 similar in use to the functions found in "pthreads". However for most
704 purposes, queues are simpler to use and more intuitive. See
705 threads::shared for more details.
706
707 Giving up control
708
709 There are times when you may find it useful to have a thread explicitly
710 give up the CPU to another thread. You may be doing something proces‐
711 sor-intensive and want to make sure that the user-interface thread gets
712 called frequently. Regardless, there are times that you might want a
713 thread to give up the processor.
714
715 Perl's threading package provides the yield() function that does this.
716 yield() is pretty straightforward, and works like this:
717
718 use threads;
719
720 sub loop {
721 my $thread = shift;
722 my $foo = 50;
723 while($foo--) { print "in thread $thread\n" }
724 threads->yield;
725 $foo = 50;
726 while($foo--) { print "in thread $thread\n" }
727 }
728
729 my $thread1 = threads->new(\&loop, 'first');
730 my $thread2 = threads->new(\&loop, 'second');
731 my $thread3 = threads->new(\&loop, 'third');
732
733 It is important to remember that yield() is only a hint to give up the
734 CPU, it depends on your hardware, OS and threading libraries what actu‐
735 ally happens. On many operating systems, yield() is a no-op. There‐
736 fore it is important to note that one should not build the scheduling
737 of the threads around yield() calls. It might work on your platform but
738 it won't work on another platform.
739
741 We've covered the workhorse parts of Perl's threading package, and with
742 these tools you should be well on your way to writing threaded code and
743 packages. There are a few useful little pieces that didn't really fit
744 in anyplace else.
745
746 What Thread Am I In?
747
748 The "threads->self" class method provides your program with a way to
749 get an object representing the thread it's currently in. You can use
750 this object in the same way as the ones returned from thread creation.
751
752 Thread IDs
753
754 tid() is a thread object method that returns the thread ID of the
755 thread the object represents. Thread IDs are integers, with the main
756 thread in a program being 0. Currently Perl assigns a unique tid to
757 every thread ever created in your program, assigning the first thread
758 to be created a tid of 1, and increasing the tid by 1 for each new
759 thread that's created.
760
761 Are These Threads The Same?
762
763 The equal() method takes two thread objects and returns true if the
764 objects represent the same thread, and false if they don't.
765
766 Thread objects also have an overloaded == comparison so that you can do
767 comparison on them as you would with normal objects.
768
769 What Threads Are Running?
770
771 "threads->list" returns a list of thread objects, one for each thread
772 that's currently running and not detached. Handy for a number of
773 things, including cleaning up at the end of your program:
774
775 # Loop through all the threads
776 foreach $thr (threads->list) {
777 # Don't join the main thread or ourselves
778 if ($thr->tid && !threads::equal($thr, threads->self)) {
779 $thr->join;
780 }
781 }
782
783 If some threads have not finished running when the main Perl thread
784 ends, Perl will warn you about it and die, since it is impossible for
785 Perl to clean up itself while other threads are running
786
788 Confused yet? It's time for an example program to show some of the
789 things we've covered. This program finds prime numbers using threads.
790
791 1 #!/usr/bin/perl -w
792 2 # prime-pthread, courtesy of Tom Christiansen
793 3
794 4 use strict;
795 5
796 6 use threads;
797 7 use Thread::Queue;
798 8
799 9 my $stream = new Thread::Queue;
800 10 my $kid = new threads(\&check_num, $stream, 2);
801 11
802 12 for my $i ( 3 .. 1000 ) {
803 13 $stream->enqueue($i);
804 14 }
805 15
806 16 $stream->enqueue(undef);
807 17 $kid->join;
808 18
809 19 sub check_num {
810 20 my ($upstream, $cur_prime) = @_;
811 21 my $kid;
812 22 my $downstream = new Thread::Queue;
813 23 while (my $num = $upstream->dequeue) {
814 24 next unless $num % $cur_prime;
815 25 if ($kid) {
816 26 $downstream->enqueue($num);
817 27 } else {
818 28 print "Found prime $num\n";
819 29 $kid = new threads(\&check_num, $downstream, $num);
820 30 }
821 31 }
822 32 $downstream->enqueue(undef) if $kid;
823 33 $kid->join if $kid;
824 34 }
825
826 This program uses the pipeline model to generate prime numbers. Each
827 thread in the pipeline has an input queue that feeds numbers to be
828 checked, a prime number that it's responsible for, and an output queue
829 into which it funnels numbers that have failed the check. If the
830 thread has a number that's failed its check and there's no child
831 thread, then the thread must have found a new prime number. In that
832 case, a new child thread is created for that prime and stuck on the end
833 of the pipeline.
834
835 This probably sounds a bit more confusing than it really is, so let's
836 go through this program piece by piece and see what it does. (For
837 those of you who might be trying to remember exactly what a prime num‐
838 ber is, it's a number that's only evenly divisible by itself and 1)
839
840 The bulk of the work is done by the check_num() subroutine, which takes
841 a reference to its input queue and a prime number that it's responsible
842 for. After pulling in the input queue and the prime that the subrou‐
843 tine's checking (line 20), we create a new queue (line 22) and reserve
844 a scalar for the thread that we're likely to create later (line 21).
845
846 The while loop from lines 23 to line 31 grabs a scalar off the input
847 queue and checks against the prime this thread is responsible for.
848 Line 24 checks to see if there's a remainder when we modulo the number
849 to be checked against our prime. If there is one, the number must not
850 be evenly divisible by our prime, so we need to either pass it on to
851 the next thread if we've created one (line 26) or create a new thread
852 if we haven't.
853
854 The new thread creation is line 29. We pass on to it a reference to
855 the queue we've created, and the prime number we've found.
856
857 Finally, once the loop terminates (because we got a 0 or undef in the
858 queue, which serves as a note to die), we pass on the notice to our
859 child and wait for it to exit if we've created a child (lines 32 and
860 37).
861
862 Meanwhile, back in the main thread, we create a queue (line 9) and the
863 initial child thread (line 10), and pre-seed it with the first prime:
864 2. Then we queue all the numbers from 3 to 1000 for checking (lines
865 12-14), then queue a die notice (line 16) and wait for the first child
866 thread to terminate (line 17). Because a child won't die until its
867 child has died, we know that we're done once we return from the join.
868
869 That's how it works. It's pretty simple; as with many Perl programs,
870 the explanation is much longer than the program.
871
873 Some background on thread implementations from the operating system
874 viewpoint. There are three basic categories of threads: user-mode
875 threads, kernel threads, and multiprocessor kernel threads.
876
877 User-mode threads are threads that live entirely within a program and
878 its libraries. In this model, the OS knows nothing about threads. As
879 far as it's concerned, your process is just a process.
880
881 This is the easiest way to implement threads, and the way most OSes
882 start. The big disadvantage is that, since the OS knows nothing about
883 threads, if one thread blocks they all do. Typical blocking activities
884 include most system calls, most I/O, and things like sleep().
885
886 Kernel threads are the next step in thread evolution. The OS knows
887 about kernel threads, and makes allowances for them. The main differ‐
888 ence between a kernel thread and a user-mode thread is blocking. With
889 kernel threads, things that block a single thread don't block other
890 threads. This is not the case with user-mode threads, where the kernel
891 blocks at the process level and not the thread level.
892
893 This is a big step forward, and can give a threaded program quite a
894 performance boost over non-threaded programs. Threads that block per‐
895 forming I/O, for example, won't block threads that are doing other
896 things. Each process still has only one thread running at once,
897 though, regardless of how many CPUs a system might have.
898
899 Since kernel threading can interrupt a thread at any time, they will
900 uncover some of the implicit locking assumptions you may make in your
901 program. For example, something as simple as "$a = $a + 2" can behave
902 unpredictably with kernel threads if $a is visible to other threads, as
903 another thread may have changed $a between the time it was fetched on
904 the right hand side and the time the new value is stored.
905
906 Multiprocessor kernel threads are the final step in thread support.
907 With multiprocessor kernel threads on a machine with multiple CPUs, the
908 OS may schedule two or more threads to run simultaneously on different
909 CPUs.
910
911 This can give a serious performance boost to your threaded program,
912 since more than one thread will be executing at the same time. As a
913 tradeoff, though, any of those nagging synchronization issues that
914 might not have shown with basic kernel threads will appear with a
915 vengeance.
916
917 In addition to the different levels of OS involvement in threads, dif‐
918 ferent OSes (and different thread implementations for a particular OS)
919 allocate CPU cycles to threads in different ways.
920
921 Cooperative multitasking systems have running threads give up control
922 if one of two things happen. If a thread calls a yield function, it
923 gives up control. It also gives up control if the thread does some‐
924 thing that would cause it to block, such as perform I/O. In a coopera‐
925 tive multitasking implementation, one thread can starve all the others
926 for CPU time if it so chooses.
927
928 Preemptive multitasking systems interrupt threads at regular intervals
929 while the system decides which thread should run next. In a preemptive
930 multitasking system, one thread usually won't monopolize the CPU.
931
932 On some systems, there can be cooperative and preemptive threads run‐
933 ning simultaneously. (Threads running with realtime priorities often
934 behave cooperatively, for example, while threads running at normal pri‐
935 orities behave preemptively.)
936
937 Most modern operating systems support preemptive multitasking nowadays.
938
940 The main thing to bear in mind when comparing ithreads to other thread‐
941 ing models is the fact that for each new thread created, a complete
942 copy of all the variables and data of the parent thread has to be
943 taken. Thus thread creation can be quite expensive, both in terms of
944 memory usage and time spent in creation. The ideal way to reduce these
945 costs is to have a relatively short number of long-lived threads, all
946 created fairly early on - before the base thread has accumulated too
947 much data. Of course, this may not always be possible, so compromises
948 have to be made. However, after a thread has been created, its perfor‐
949 mance and extra memory usage should be little different than ordinary
950 code.
951
952 Also note that under the current implementation, shared variables use a
953 little more memory and are a little slower than ordinary variables.
954
956 Note that while threads themselves are separate execution threads and
957 Perl data is thread-private unless explicitly shared, the threads can
958 affect process-scope state, affecting all the threads.
959
960 The most common example of this is changing the current working direc‐
961 tory using chdir(). One thread calls chdir(), and the working direc‐
962 tory of all the threads changes.
963
964 Even more drastic example of a process-scope change is chroot(): the
965 root directory of all the threads changes, and no thread can undo it
966 (as opposed to chdir()).
967
968 Further examples of process-scope changes include umask() and changing
969 uids/gids.
970
971 Thinking of mixing fork() and threads? Please lie down and wait until
972 the feeling passes. Be aware that the semantics of fork() vary between
973 platforms. For example, some UNIX systems copy all the current threads
974 into the child process, while others only copy the thread that called
975 fork(). You have been warned!
976
977 Similarly, mixing signals and threads should not be attempted. Imple‐
978 mentations are platform-dependent, and even the POSIX semantics may not
979 be what you expect (and Perl doesn't even give you the full POSIX API).
980
982 Whether various library calls are thread-safe is outside the control of
983 Perl. Calls often suffering from not being thread-safe include: local‐
984 time(), gmtime(), get{gr,host,net,proto,serv,pw}*(), readdir(), rand(),
985 and srand() -- in general, calls that depend on some global external
986 state.
987
988 If the system Perl is compiled in has thread-safe variants of such
989 calls, they will be used. Beyond that, Perl is at the mercy of the
990 thread-safety or -unsafety of the calls. Please consult your C library
991 call documentation.
992
993 On some platforms the thread-safe library interfaces may fail if the
994 result buffer is too small (for example the user group databases may be
995 rather large, and the reentrant interfaces may have to carry around a
996 full snapshot of those databases). Perl will start with a small buf‐
997 fer, but keep retrying and growing the result buffer until the result
998 fits. If this limitless growing sounds bad for security or memory con‐
999 sumption reasons you can recompile Perl with PERL_REENTRANT_MAXSIZE
1000 defined to the maximum number of bytes you will allow.
1001
1003 A complete thread tutorial could fill a book (and has, many times), but
1004 with what we've covered in this introduction, you should be well on
1005 your way to becoming a threaded Perl expert.
1006
1008 Here's a short bibliography courtesy of Jürgen Christoffel:
1009
1010 Introductory Texts
1011
1012 Birrell, Andrew D. An Introduction to Programming with Threads. Digital
1013 Equipment Corporation, 1989, DEC-SRC Research Report #35 online as
1014 http://gate‐
1015 keeper.dec.com/pub/DEC/SRC/research-reports/abstracts/src-rr-035.html
1016 (highly recommended)
1017
1018 Robbins, Kay. A., and Steven Robbins. Practical Unix Programming: A
1019 Guide to Concurrency, Communication, and Multithreading. Prentice-Hall,
1020 1996.
1021
1022 Lewis, Bill, and Daniel J. Berg. Multithreaded Programming with
1023 Pthreads. Prentice Hall, 1997, ISBN 0-13-443698-9 (a well-written
1024 introduction to threads).
1025
1026 Nelson, Greg (editor). Systems Programming with Modula-3. Prentice
1027 Hall, 1991, ISBN 0-13-590464-1.
1028
1029 Nichols, Bradford, Dick Buttlar, and Jacqueline Proulx Farrell.
1030 Pthreads Programming. O'Reilly & Associates, 1996, ISBN 156592-115-1
1031 (covers POSIX threads).
1032
1033 OS-Related References
1034
1035 Boykin, Joseph, David Kirschen, Alan Langerman, and Susan LoVerso. Pro‐
1036 gramming under Mach. Addison-Wesley, 1994, ISBN 0-201-52739-1.
1037
1038 Tanenbaum, Andrew S. Distributed Operating Systems. Prentice Hall,
1039 1995, ISBN 0-13-219908-4 (great textbook).
1040
1041 Silberschatz, Abraham, and Peter B. Galvin. Operating System Concepts,
1042 4th ed. Addison-Wesley, 1995, ISBN 0-201-59292-4
1043
1044 Other References
1045
1046 Arnold, Ken and James Gosling. The Java Programming Language, 2nd ed.
1047 Addison-Wesley, 1998, ISBN 0-201-31006-6.
1048
1049 comp.programming.threads FAQ, <http://www.serpen‐
1050 tine.com/~bos/threads-faq/>
1051
1052 Le Sergent, T. and B. Berthomieu. "Incremental MultiThreaded Garbage
1053 Collection on Virtually Shared Memory Architectures" in Memory Manage‐
1054 ment: Proc. of the International Workshop IWMM 92, St. Malo, France,
1055 September 1992, Yves Bekkers and Jacques Cohen, eds. Springer, 1992,
1056 ISBN 3540-55940-X (real-life thread applications).
1057
1058 Artur Bergman, "Where Wizards Fear To Tread", June 11, 2002,
1059 <http://www.perl.com/pub/a/2002/06/11/threads.html>
1060
1062 Thanks (in no particular order) to Chaim Frenkel, Steve Fink, Gurusamy
1063 Sarathy, Ilya Zakharevich, Benjamin Sugars, Jürgen Christoffel, Joshua
1064 Pritikin, and Alan Burlison, for their help in reality-checking and
1065 polishing this article. Big thanks to Tom Christiansen for his rewrite
1066 of the prime number generator.
1067
1069 Dan Sugalski <dan@sidhe.org<gt>
1070
1071 Slightly modified by Arthur Bergman to fit the new thread model/module.
1072
1073 Reworked slightly by Jörg Walter <jwalt@cpan.org<gt> to be more concise
1074 about thread-safety of perl code.
1075
1076 Rearranged slightly by Elizabeth Mattijsen <liz@dijkmat.nl<gt> to put
1077 less emphasis on yield().
1078
1080 The original version of this article originally appeared in The Perl
1081 Journal #10, and is copyright 1998 The Perl Journal. It appears cour‐
1082 tesy of Jon Orwant and The Perl Journal. This document may be distrib‐
1083 uted under the same terms as Perl itself.
1084
1085 For more information please see threads and threads::shared.
1086
1087
1088
1089perl v5.8.8 2006-01-07 PERLTHRTUT(1)