This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
[DOC PATCH] perlthrtut proofreading
[perl5.git] / pod / perlthrtut.pod
CommitLineData
2605996a
JH
1=head1 NAME
2
3perlthrtut - tutorial on threads in Perl
4
5=head1 DESCRIPTION
6
53d7eaa8
JH
7B<NOTE>: this tutorial describes the new Perl threading flavour
8introduced in Perl 5.6.0 called interpreter threads, or ithreads
9for short. There is another older perl threading flavour called
10the 5.005 model, unsurprisingly for 5.005 versions of Perl.
2a4bf773 11
53d7eaa8 12You can see which (or neither) threading flavour you have by
6eded8f3 13running C<perl -V> and looking at the C<Platform> section.
53d7eaa8
JH
14If you have C<useithreads=define> you have ithreads, if you
15have C<use5005threads=define> you have 5.005 threads.
16If you have neither, you don't have any thread support built in.
17If you have both, you are in trouble.
2605996a 18
2605996a 19
c975c451
AB
20=head1 What Is A Thread Anyway?
21
22A thread is a flow of control through a program with a single
23execution point.
24
25Sounds an awful lot like a process, doesn't it? Well, it should.
26Threads are one of the pieces of a process. Every process has at least
27one thread and, up until now, every process running Perl had only one
28thread. With 5.8, though, you can create extra threads. We're going
29to show you how, when, and why.
30
31=head1 Threaded Program Models
32
33There are three basic ways that you can structure a threaded
34program. Which model you choose depends on what you need your program
35to do. For many non-trivial threaded programs you'll need to choose
36different models for different pieces of your program.
37
38=head2 Boss/Worker
39
40The boss/worker model usually has one `boss' thread and one or more
41`worker' threads. The boss thread gathers or generates tasks that need
42to be done, then parcels those tasks out to the appropriate worker
43thread.
44
45This model is common in GUI and server programs, where a main thread
46waits for some event and then passes that event to the appropriate
47worker threads for processing. Once the event has been passed on, the
48boss thread goes back to waiting for another event.
49
50The boss thread does relatively little work. While tasks aren't
51necessarily performed faster than with any other method, it tends to
52have the best user-response times.
53
54=head2 Work Crew
55
56In the work crew model, several threads are created that do
57essentially the same thing to different pieces of data. It closely
58mirrors classical parallel processing and vector processors, where a
59large array of processors do the exact same thing to many pieces of
60data.
61
62This model is particularly useful if the system running the program
63will distribute multiple threads across different processors. It can
64also be useful in ray tracing or rendering engines, where the
65individual threads can pass on interim results to give the user visual
66feedback.
67
68=head2 Pipeline
69
70The pipeline model divides up a task into a series of steps, and
71passes the results of one step on to the thread processing the
72next. Each thread does one thing to each piece of data and passes the
73results to the next thread in line.
74
75This model makes the most sense if you have multiple processors so two
76or more threads will be executing in parallel, though it can often
77make sense in other contexts as well. It tends to keep the individual
78tasks small and simple, as well as allowing some parts of the pipeline
79to block (on I/O or system calls, for example) while other parts keep
80going. If you're running different parts of the pipeline on different
81processors you may also take advantage of the caches on each
82processor.
83
84This model is also handy for a form of recursive programming where,
85rather than having a subroutine call itself, it instead creates
86another thread. Prime and Fibonacci generators both map well to this
87form of the pipeline model. (A version of a prime number generator is
88presented later on.)
89
90=head1 Native threads
91
92There are several different ways to implement threads on a system. How
93threads are implemented depends both on the vendor and, in some cases,
94the version of the operating system. Often the first implementation
95will be relatively simple, but later versions of the OS will be more
96sophisticated.
97
98While the information in this section is useful, it's not necessary,
99so you can skip it if you don't feel up to it.
100
6eded8f3 101There are three basic categories of threads: user-mode threads, kernel
c975c451
AB
102threads, and multiprocessor kernel threads.
103
104User-mode threads are threads that live entirely within a program and
105its libraries. In this model, the OS knows nothing about threads. As
106far as it's concerned, your process is just a process.
107
108This is the easiest way to implement threads, and the way most OSes
109start. The big disadvantage is that, since the OS knows nothing about
110threads, if one thread blocks they all do. Typical blocking activities
111include most system calls, most I/O, and things like sleep().
112
113Kernel threads are the next step in thread evolution. The OS knows
114about kernel threads, and makes allowances for them. The main
115difference between a kernel thread and a user-mode thread is
116blocking. With kernel threads, things that block a single thread don't
117block other threads. This is not the case with user-mode threads,
118where the kernel blocks at the process level and not the thread level.
119
120This is a big step forward, and can give a threaded program quite a
121performance boost over non-threaded programs. Threads that block
122performing I/O, for example, won't block threads that are doing other
123things. Each process still has only one thread running at once,
124though, regardless of how many CPUs a system might have.
125
126Since kernel threading can interrupt a thread at any time, they will
127uncover some of the implicit locking assumptions you may make in your
128program. For example, something as simple as C<$a = $a + 2> can behave
129unpredictably with kernel threads if $a is visible to other
130threads, as another thread may have changed $a between the time it
131was fetched on the right hand side and the time the new value is
132stored.
133
6eded8f3 134Multiprocessor kernel threads are the final step in thread
c975c451
AB
135support. With multiprocessor kernel threads on a machine with multiple
136CPUs, the OS may schedule two or more threads to run simultaneously on
137different CPUs.
138
139This can give a serious performance boost to your threaded program,
140since more than one thread will be executing at the same time. As a
141tradeoff, though, any of those nagging synchronization issues that
142might not have shown with basic kernel threads will appear with a
143vengeance.
144
145In addition to the different levels of OS involvement in threads,
146different OSes (and different thread implementations for a particular
147OS) allocate CPU cycles to threads in different ways.
148
149Cooperative multitasking systems have running threads give up control
150if one of two things happen. If a thread calls a yield function, it
151gives up control. It also gives up control if the thread does
152something that would cause it to block, such as perform I/O. In a
153cooperative multitasking implementation, one thread can starve all the
154others for CPU time if it so chooses.
155
156Preemptive multitasking systems interrupt threads at regular intervals
157while the system decides which thread should run next. In a preemptive
158multitasking system, one thread usually won't monopolize the CPU.
159
160On some systems, there can be cooperative and preemptive threads
161running simultaneously. (Threads running with realtime priorities
162often behave cooperatively, for example, while threads running at
163normal priorities behave preemptively.)
164
165=head1 What kind of threads are perl threads?
166
167If you have experience with other thread implementations, you might
168find that things aren't quite what you expect. It's very important to
169remember when dealing with Perl threads that Perl Threads Are Not X
170Threads, for all values of X. They aren't POSIX threads, or
171DecThreads, or Java's Green threads, or Win32 threads. There are
172similarities, and the broad concepts are the same, but if you start
173looking for implementation details you're going to be either
174disappointed or confused. Possibly both.
175
176This is not to say that Perl threads are completely different from
177everything that's ever come before--they're not. Perl's threading
178model owes a lot to other thread models, especially POSIX. Just as
179Perl is not C, though, Perl threads are not POSIX threads. So if you
180find yourself looking for mutexes, or thread priorities, it's time to
181step back a bit and think about what you want to do and how Perl can
182do it.
183
6eded8f3 184However it is important to remember that Perl threads cannot magically
c975c451 185do things unless your operating systems threads allows it. So if your
6eded8f3 186system blocks the entire process on sleep(), perl usually will as well.
c975c451
AB
187
188=head1 Threadsafe Modules
189
190The addition of threads has changed Perl's internals
191substantially. There are implications for people who write
6eded8f3
SG
192modules with XS code or external libraries. However, since the threads
193do not share data, pure Perl modules that don't interact with external
c975c451
AB
194systems should be safe. Modules that are not tagged as thread-safe should
195be tested or code reviewed before being used in production code.
196
197Not all modules that you might use are thread-safe, and you should
198always assume a module is unsafe unless the documentation says
199otherwise. This includes modules that are distributed as part of the
200core. Threads are a new feature, and even some of the standard
201modules aren't thread-safe. (*** I think ActiveState checked this for
202psuedofork, check with GSAR)
203
6eded8f3
SG
204Even if a module is threadsafe, it doesn't mean that the module is optimized
205to work well with threads. A module could possibly be rewritten to utilize
206the new features in threaded Perl to increase performance in a threaded
207environment.
c975c451
AB
208
209If you're using a module that's not thread-safe for some reason, you
210can protect yourself by using semaphores and lots of programming
211discipline to control access to the module. Semaphores are covered
212later in the article. Perl Threads Are Different
213
214=head1 Thread Basics
215
216The core L<threads> module provides the basic functions you need to write
217threaded programs. In the following sections we'll cover the basics,
218showing you what you need to do to create a threaded program. After
219that, we'll go over some of the features of the L<threads> module that
220make threaded programming easier.
221
222=head2 Basic Thread Support
223
6eded8f3 224Thread support is a Perl compile-time option - it's something that's
c975c451
AB
225turned on or off when Perl is built at your site, rather than when
226your programs are compiled. If your Perl wasn't compiled with thread
227support enabled, then any attempt to use threads will fail.
228
c975c451
AB
229Your programs can use the Config module to check whether threads are
230enabled. If your program can't run without them, you can say something
231like:
232
233 $Config{useithreads} or die "Recompile Perl with threads to run this program.";
234
235A possibly-threaded program using a possibly-threaded module might
236have code like this:
237
238 use Config;
239 use MyMod;
240
241 if ($Config{useithreads}) {
242 # We have threads
243 require MyMod_threaded;
244 import MyMod_threaded;
245 } else {
246 require MyMod_unthreaded;
247 import MyMod_unthreaded;
248 }
249
250Since code that runs both with and without threads is usually pretty
251messy, it's best to isolate the thread-specific code in its own
252module. In our example above, that's what MyMod_threaded is, and it's
253only imported if we're running on a threaded Perl.
254
255=head2 Creating Threads
256
257The L<threads> package provides the tools you need to create new
258threads. Like any other module, you need to tell Perl you want to use
259it; C<use threads> imports all the pieces you need to create basic
260threads.
261
262The simplest, straightforward way to create a thread is with new():
263
264 use threads;
265
266 $thr = threads->new(\&sub1);
267
268 sub sub1 {
269 print "In the thread\n";
270 }
271
272The new() method takes a reference to a subroutine and creates a new
273thread, which starts executing in the referenced subroutine. Control
274then passes both to the subroutine and the caller.
275
276If you need to, your program can pass parameters to the subroutine as
277part of the thread startup. Just include the list of parameters as
278part of the C<threads::new> call, like this:
279
280 use threads;
281 $Param3 = "foo";
282 $thr = threads->new(\&sub1, "Param 1", "Param 2", $Param3);
283 $thr = threads->new(\&sub1, @ParamList);
284 $thr = threads->new(\&sub1, qw(Param1 Param2 $Param3));
285
286 sub sub1 {
287 my @InboundParameters = @_;
288 print "In the thread\n";
289 print "got parameters >", join("<>", @InboundParameters), "<\n";
290 }
291
292
293The last example illustrates another feature of threads. You can spawn
294off several threads using the same subroutine. Each thread executes
295the same subroutine, but in a separate thread with a separate
296environment and potentially separate arguments.
297
298=head2 Giving up control
299
300There are times when you may find it useful to have a thread
301explicitly give up the CPU to another thread. Your threading package
302might not support preemptive multitasking for threads, for example, or
303you may be doing something compute-intensive and want to make sure
304that the user-interface thread gets called frequently. Regardless,
305there are times that you might want a thread to give up the processor.
306
307Perl's threading package provides the yield() function that does
308this. yield() is pretty straightforward, and works like this:
309
310 use threads;
311
312 sub loop {
313 my $thread = shift;
314 my $foo = 50;
315 while($foo--) { print "in thread $thread\n" }
316 threads->yield();
317 $foo = 50;
6eded8f3 318 while($foo--) { print "in thread $thread\n" }
c975c451
AB
319 }
320
321 my $thread1 = threads->new(\&loop, 'first');
322 my $thread2 = threads->new(\&loop, 'second');
323 my $thread3 = threads->new(\&loop, 'third');
324
325It is important to remember that yield() is only a hint to give up the CPU,
326it depends on your hardware, OS and threading libraries what actually happens.
327Therefore it is important to note that one should not build the scheduling of
328the threads around yield() calls. It might work on your platform but it won't
329work on another platform.
330
331=head2 Waiting For A Thread To Exit
332
333Since threads are also subroutines, they can return values. To wait
6eded8f3
SG
334for a thread to exit and extract any values it might return, you can
335use the join() method:
c975c451
AB
336
337 use threads;
338 $thr = threads->new(\&sub1);
339
340 @ReturnData = $thr->join;
341 print "Thread returned @ReturnData";
342
343 sub sub1 { return "Fifty-six", "foo", 2; }
344
345In the example above, the join() method returns as soon as the thread
346ends. In addition to waiting for a thread to finish and gathering up
347any values that the thread might have returned, join() also performs
348any OS cleanup necessary for the thread. That cleanup might be
349important, especially for long-running programs that spawn lots of
350threads. If you don't want the return values and don't want to wait
351for the thread to finish, you should call the detach() method
352instead. detach() is covered later in the article.
353
354=head2 Ignoring A Thread
355
356join() does three things: it waits for a thread to exit, cleans up
357after it, and returns any data the thread may have produced. But what
358if you're not interested in the thread's return values, and you don't
359really care when the thread finishes? All you want is for the thread
360to get cleaned up after when it's done.
361
362In this case, you use the detach() method. Once a thread is detached,
363it'll run until it's finished, then Perl will clean up after it
364automatically.
365
366 use threads;
6eded8f3 367 $thr = threads->new(\&sub1); # Spawn the thread
c975c451
AB
368
369 $thr->detach; # Now we officially don't care any more
370
371 sub sub1 {
372 $a = 0;
373 while (1) {
374 $a++;
375 print "\$a is $a\n";
376 sleep 1;
377 }
378 }
379
380
381Once a thread is detached, it may not be joined, and any output that
382it might have produced (if it was done and waiting for a join) is
383lost.
384
385=head1 Threads And Data
386
387Now that we've covered the basics of threads, it's time for our next
388topic: data. Threading introduces a couple of complications to data
389access that non-threaded programs never need to worry about.
390
391=head2 Shared And Unshared Data
392
393The biggest difference between perl threading and the old 5.005 style
394threading, or most other threading systems out there, is that all data
395is not shared. When a new perl thread is created all data is cloned
396and is private to that thread!
397
398To make use of threading however, one usually want the threads to share
6eded8f3
SG
399data between each other. This is done with the L<threads::shared> module
400and the C< : shared> attribute:
c975c451
AB
401
402 use threads;
403 use threads::shared;
404 my $foo : shared = 1;
405 my $bar = 1;
406 threads->new(sub { $foo++; $bar++ })->join;
407
408 print "$foo\n"; #prints 2 since $foo is shared
6eded8f3 409 print "$bar\n"; #prints 1 since $bar is not shared
c975c451 410
6eded8f3 411=head2 Thread Pitfalls: Races
c975c451
AB
412
413While threads bring a new set of useful tools, they also bring a
414number of pitfalls. One pitfall is the race condition:
415
416 use threads;
417 use threads::shared;
418 my $a : shared = 1;
419 $thr1 = threads->new(\&sub1);
420 $thr2 = threads->new(\&sub2);
421
422 $thr1->join;
423 $thr2->join;
424 print "$a\n";
425
426 sub sub1 { $foo = $a; $a = $foo + 1; }
427 sub sub2 { $bar = $a; $a = $bar + 1; }
428
429What do you think $a will be? The answer, unfortunately, is "it
430depends." Both sub1() and sub2() access the global variable $a, once
431to read and once to write. Depending on factors ranging from your
432thread implementation's scheduling algorithm to the phase of the moon,
433$a can be 2 or 3.
434
435Race conditions are caused by unsynchronized access to shared
436data. Without explicit synchronization, there's no way to be sure that
437nothing has happened to the shared data between the time you access it
438and the time you update it. Even this simple code fragment has the
439possibility of error:
440
441 use threads;
442 my $a : shared = 2;
443 my $b : shared;
444 my $c : shared;
445 my $thr1 = threads->create(sub { $b = $a; $a = $b + 1; });
446 my $thr2 = threads->create(sub { $c = $a; $a = $c + 1; });
447 $thr1->join();
448 $thr2->join();
449
450Two threads both access $a. Each thread can potentially be interrupted
451at any point, or be executed in any order. At the end, $a could be 3
452or 4, and both $b and $c could be 2 or 3.
453
454Whenever your program accesses data or resources that can be accessed
455by other threads, you must take steps to coordinate access or risk
456data corruption and race conditions.
457
458=head2 Controlling access: lock()
459
460The lock() function takes a shared variable and puts a lock on it.
461No other thread may lock the variable until the locking thread exits
462the innermost block containing the lock.
463Using lock() is straightforward:
464
465 use threads;
466 my $a : shared = 4;
467 $thr1 = threads->new(sub {
468 $foo = 12;
469 {
470 lock ($a); # Block until we get access to $a
471 $b = $a;
472 $a = $b * $foo;
473 }
474 print "\$foo was $foo\n";
475 });
476 $thr2 = threads->new(sub {
477 $bar = 7;
478 {
479 lock ($a); # Block until we can get access to $a
480 $c = $a;
481 $a = $c * $bar;
482 }
483 print "\$bar was $bar\n";
484 });
485 $thr1->join;
486 $thr2->join;
487 print "\$a is $a\n";
488
489lock() blocks the thread until the variable being locked is
490available. When lock() returns, your thread can be sure that no other
491thread can lock that variable until the innermost block containing the
492lock exits.
493
494It's important to note that locks don't prevent access to the variable
495in question, only lock attempts. This is in keeping with Perl's
496longstanding tradition of courteous programming, and the advisory file
497locking that flock() gives you.
498
499You may lock arrays and hashes as well as scalars. Locking an array,
500though, will not block subsequent locks on array elements, just lock
501attempts on the array itself.
502
503Finally, locks are recursive, which means it's okay for a thread to
504lock a variable more than once. The lock will last until the outermost
505lock() on the variable goes out of scope.
506
507=head2 Thread Pitfall: Deadlocks
508
509Locks are a handy tool to synchronize access to data. Using them
510properly is the key to safe shared data. Unfortunately, locks aren't
511without their dangers. Consider the following code:
512
513 use threads;
514 my $a : shared = 4;
515 my $b : shared = "foo";
516 my $thr1 = threads->new(sub {
517 lock($a);
518 yield;
519 sleep 20;
520 lock ($b);
521 });
522 my $thr2 = threads->new(sub {
523 lock($b);
524 yield;
525 sleep 20;
526 lock ($a);
527 });
528
529This program will probably hang until you kill it. The only way it
530won't hang is if one of the two async() routines acquires both locks
531first. A guaranteed-to-hang version is more complicated, but the
532principle is the same.
533
534The first thread spawned by async() will grab a lock on $a then, a
535second or two later, try to grab a lock on $b. Meanwhile, the second
536thread grabs a lock on $b, then later tries to grab a lock on $a. The
537second lock attempt for both threads will block, each waiting for the
538other to release its lock.
539
540This condition is called a deadlock, and it occurs whenever two or
541more threads are trying to get locks on resources that the others
542own. Each thread will block, waiting for the other to release a lock
543on a resource. That never happens, though, since the thread with the
544resource is itself waiting for a lock to be released.
545
546There are a number of ways to handle this sort of problem. The best
547way is to always have all threads acquire locks in the exact same
548order. If, for example, you lock variables $a, $b, and $c, always lock
549$a before $b, and $b before $c. It's also best to hold on to locks for
550as short a period of time to minimize the risks of deadlock.
551
552=head2 Queues: Passing Data Around
553
554A queue is a special thread-safe object that lets you put data in one
555end and take it out the other without having to worry about
556synchronization issues. They're pretty straightforward, and look like
557this:
558
559 use threads;
560 use threads::shared::queue;
561
562 my $DataQueue = new threads::shared::queue;
563 $thr = threads->new(sub {
564 while ($DataElement = $DataQueue->dequeue) {
565 print "Popped $DataElement off the queue\n";
566 }
567 });
568
569 $DataQueue->enqueue(12);
570 $DataQueue->enqueue("A", "B", "C");
571 $DataQueue->enqueue(\$thr);
572 sleep 10;
573 $DataQueue->enqueue(undef);
574 $thr->join();
575
6eded8f3
SG
576You create the queue with C<new threads::shared::queue>. Then you can
577add lists of scalars onto the end with enqueue(), and pop scalars off
578the front of it with dequeue(). A queue has no fixed size, and can grow
579as needed to hold everything pushed on to it.
c975c451
AB
580
581If a queue is empty, dequeue() blocks until another thread enqueues
582something. This makes queues ideal for event loops and other
583communications between threads.
584
585
586=head1 Threads And Code
587
588In addition to providing thread-safe access to data via locks and
589queues, threaded Perl also provides general-purpose semaphores for
590coarser synchronization than locks provide and thread-safe access to
591entire subroutines.
592
593=head2 Semaphores: Synchronizing Data Access
594
595Semaphores are a kind of generic locking mechanism. Unlike lock, which
596gets a lock on a particular scalar, Perl doesn't associate any
597particular thing with a semaphore so you can use them to control
598access to anything you like. In addition, semaphores can allow more
599than one thread to access a resource at once, though by default
600semaphores only allow one thread access at a time.
2605996a
JH
601
602=over 4
603
c975c451
AB
604=item Basic semaphores
605
606Semaphores have two methods, down and up. down decrements the resource
607count, while up increments it. down calls will block if the
608semaphore's current count would decrement below zero. This program
609gives a quick demonstration:
610
611 use threads qw(yield);
612 use threads::shared::semaphore;
613 my $semaphore = new threads::shared::semaphore;
614 $GlobalVariable = 0;
2605996a 615
c975c451
AB
616 $thr1 = new threads \&sample_sub, 1;
617 $thr2 = new threads \&sample_sub, 2;
618 $thr3 = new threads \&sample_sub, 3;
2605996a 619
c975c451
AB
620 sub sample_sub {
621 my $SubNumber = shift @_;
622 my $TryCount = 10;
623 my $LocalCopy;
624 sleep 1;
625 while ($TryCount--) {
626 $semaphore->down;
627 $LocalCopy = $GlobalVariable;
628 print "$TryCount tries left for sub $SubNumber (\$GlobalVariable is $GlobalVariable)\n";
629 yield;
630 sleep 2;
631 $LocalCopy++;
632 $GlobalVariable = $LocalCopy;
633 $semaphore->up;
634 }
635 }
6eded8f3 636
c975c451
AB
637 $thr1->join();
638 $thr2->join();
639 $thr3->join();
2605996a 640
c975c451
AB
641The three invocations of the subroutine all operate in sync. The
642semaphore, though, makes sure that only one thread is accessing the
643global variable at once.
2605996a 644
c975c451 645=item Advanced Semaphores
2605996a 646
c975c451
AB
647By default, semaphores behave like locks, letting only one thread
648down() them at a time. However, there are other uses for semaphores.
2605996a 649
6eded8f3
SG
650Each semaphore has a counter attached to it. By default, semaphores are
651created with the counter set to one, down() decrements the counter by
652one, and up() increments by one. However, we can override any or all
653of these defaults simply by passing in different values:
654
655 use threads;
656 use threads::shared::semaphore;
657 my $semaphore = threads::shared::semaphore->new(5);
658 # Creates a semaphore with the counter set to five
659
660 $thr1 = threads->new(\&sub1);
661 $thr2 = threads->new(\&sub1);
662
663 sub sub1 {
664 $semaphore->down(5); # Decrements the counter by five
665 # Do stuff here
666 $semaphore->up(5); # Increment the counter by five
667 }
668
669 $thr1->detach();
670 $thr2->detach();
671
672If down() attempts to decrement the counter below zero, it blocks until
673the counter is large enough. Note that while a semaphore can be created
674with a starting count of zero, any up() or down() always changes the
675counter by at least one, and so $semaphore->down(0) is the same as
676$semaphore->down(1).
2605996a 677
c975c451
AB
678The question, of course, is why would you do something like this? Why
679create a semaphore with a starting count that's not one, or why
680decrement/increment it by more than one? The answer is resource
681availability. Many resources that you want to manage access for can be
682safely used by more than one thread at once.
2605996a 683
c975c451
AB
684For example, let's take a GUI driven program. It has a semaphore that
685it uses to synchronize access to the display, so only one thread is
686ever drawing at once. Handy, but of course you don't want any thread
687to start drawing until things are properly set up. In this case, you
688can create a semaphore with a counter set to zero, and up it when
689things are ready for drawing.
2605996a 690
c975c451
AB
691Semaphores with counters greater than one are also useful for
692establishing quotas. Say, for example, that you have a number of
693threads that can do I/O at once. You don't want all the threads
694reading or writing at once though, since that can potentially swamp
695your I/O channels, or deplete your process' quota of filehandles. You
696can use a semaphore initialized to the number of concurrent I/O
697requests (or open files) that you want at any one time, and have your
698threads quietly block and unblock themselves.
2605996a 699
c975c451
AB
700Larger increments or decrements are handy in those cases where a
701thread needs to check out or return a number of resources at once.
2605996a
JH
702
703=back
704
c975c451
AB
705=head1 General Thread Utility Routines
706
707We've covered the workhorse parts of Perl's threading package, and
708with these tools you should be well on your way to writing threaded
709code and packages. There are a few useful little pieces that didn't
710really fit in anyplace else.
711
712=head2 What Thread Am I In?
713
6eded8f3 714The C<threads->self> method provides your program with a way to get an
c975c451 715object representing the thread it's currently in. You can use this
6eded8f3 716object in the same way as the ones returned from thread creation.
c975c451
AB
717
718=head2 Thread IDs
719
720tid() is a thread object method that returns the thread ID of the
721thread the object represents. Thread IDs are integers, with the main
722thread in a program being 0. Currently Perl assigns a unique tid to
723every thread ever created in your program, assigning the first thread
724to be created a tid of 1, and increasing the tid by 1 for each new
725thread that's created.
726
727=head2 Are These Threads The Same?
728
729The equal() method takes two thread objects and returns true
730if the objects represent the same thread, and false if they don't.
731
732Thread objects also have an overloaded == comparison so that you can do
733comparison on them as you would with normal objects.
734
735=head2 What Threads Are Running?
736
737threads->list returns a list of thread objects, one for each thread
738that's currently running and not detached. Handy for a number of things,
739including cleaning up at the end of your program:
740
741 # Loop through all the threads
742 foreach $thr (threads->list) {
743 # Don't join the main thread or ourselves
744 if ($thr->tid && !threads::equal($thr, threads->self)) {
745 $thr->join;
746 }
747 }
748
6eded8f3 749If some threads have not finished running when the main perl thread
c975c451 750ends, perl will warn you about it and die, since it is impossible for perl
6eded8f3 751to clean up itself while other threads are running
c975c451
AB
752
753=head1 A Complete Example
754
755Confused yet? It's time for an example program to show some of the
756things we've covered. This program finds prime numbers using threads.
757
758 1 #!/usr/bin/perl -w
759 2 # prime-pthread, courtesy of Tom Christiansen
760 3
761 4 use strict;
762 5
763 6 use threads;
764 7 use threads::shared::queue;
765 8
766 9 my $stream = new threads::shared::queue;
767 10 my $kid = new threads(\&check_num, $stream, 2);
768 11
769 12 for my $i ( 3 .. 1000 ) {
770 13 $stream->enqueue($i);
771 14 }
772 15
773 16 $stream->enqueue(undef);
774 17 $kid->join();
775 18
776 19 sub check_num {
777 20 my ($upstream, $cur_prime) = @_;
778 21 my $kid;
779 22 my $downstream = new threads::shared::queue;
780 23 while (my $num = $upstream->dequeue) {
781 24 next unless $num % $cur_prime;
782 25 if ($kid) {
783 26 $downstream->enqueue($num);
784 27 } else {
785 28 print "Found prime $num\n";
786 29 $kid = new threads(\&check_num, $downstream, $num);
787 30 }
788 31 }
789 32 $downstream->enqueue(undef) if $kid;
790 33 $kid->join() if $kid;
791 34 }
792
793This program uses the pipeline model to generate prime numbers. Each
794thread in the pipeline has an input queue that feeds numbers to be
795checked, a prime number that it's responsible for, and an output queue
6eded8f3 796that into which it funnels numbers that have failed the check. If the thread
c975c451
AB
797has a number that's failed its check and there's no child thread, then
798the thread must have found a new prime number. In that case, a new
799child thread is created for that prime and stuck on the end of the
800pipeline.
801
6eded8f3 802This probably sounds a bit more confusing than it really is, so let's
c975c451
AB
803go through this program piece by piece and see what it does. (For
804those of you who might be trying to remember exactly what a prime
805number is, it's a number that's only evenly divisible by itself and 1)
806
807The bulk of the work is done by the check_num() subroutine, which
808takes a reference to its input queue and a prime number that it's
809responsible for. After pulling in the input queue and the prime that
810the subroutine's checking (line 20), we create a new queue (line 22)
811and reserve a scalar for the thread that we're likely to create later
812(line 21).
813
814The while loop from lines 23 to line 31 grabs a scalar off the input
815queue and checks against the prime this thread is responsible
816for. Line 24 checks to see if there's a remainder when we modulo the
817number to be checked against our prime. If there is one, the number
818must not be evenly divisible by our prime, so we need to either pass
819it on to the next thread if we've created one (line 26) or create a
820new thread if we haven't.
821
822The new thread creation is line 29. We pass on to it a reference to
823the queue we've created, and the prime number we've found.
824
825Finally, once the loop terminates (because we got a 0 or undef in the
826queue, which serves as a note to die), we pass on the notice to our
6eded8f3 827child and wait for it to exit if we've created a child (lines 32 and
c975c451
AB
82837).
829
830Meanwhile, back in the main thread, we create a queue (line 9) and the
831initial child thread (line 10), and pre-seed it with the first prime:
8322. Then we queue all the numbers from 3 to 1000 for checking (lines
83312-14), then queue a die notice (line 16) and wait for the first child
834thread to terminate (line 17). Because a child won't die until its
835child has died, we know that we're done once we return from the join.
836
837That's how it works. It's pretty simple; as with many Perl programs,
838the explanation is much longer than the program.
839
840=head1 Conclusion
841
842A complete thread tutorial could fill a book (and has, many times),
6eded8f3
SG
843but with what we've covered in this introduction, you should be well
844on your way to becoming a threaded Perl expert.
c975c451
AB
845
846=head1 Bibliography
847
848Here's a short bibliography courtesy of Jürgen Christoffel:
849
850=head2 Introductory Texts
851
852Birrell, Andrew D. An Introduction to Programming with
853Threads. Digital Equipment Corporation, 1989, DEC-SRC Research Report
854#35 online as
6eded8f3
SG
855http://gatekeeper.dec.com/pub/DEC/SRC/research-reports/abstracts/src-rr-035.html
856(highly recommended)
c975c451
AB
857
858Robbins, Kay. A., and Steven Robbins. Practical Unix Programming: A
859Guide to Concurrency, Communication, and
860Multithreading. Prentice-Hall, 1996.
861
862Lewis, Bill, and Daniel J. Berg. Multithreaded Programming with
863Pthreads. Prentice Hall, 1997, ISBN 0-13-443698-9 (a well-written
864introduction to threads).
865
866Nelson, Greg (editor). Systems Programming with Modula-3. Prentice
867Hall, 1991, ISBN 0-13-590464-1.
868
869Nichols, Bradford, Dick Buttlar, and Jacqueline Proulx Farrell.
870Pthreads Programming. O'Reilly & Associates, 1996, ISBN 156592-115-1
871(covers POSIX threads).
872
873=head2 OS-Related References
874
875Boykin, Joseph, David Kirschen, Alan Langerman, and Susan
876LoVerso. Programming under Mach. Addison-Wesley, 1994, ISBN
8770-201-52739-1.
878
879Tanenbaum, Andrew S. Distributed Operating Systems. Prentice Hall,
8801995, ISBN 0-13-219908-4 (great textbook).
881
882Silberschatz, Abraham, and Peter B. Galvin. Operating System Concepts,
8834th ed. Addison-Wesley, 1995, ISBN 0-201-59292-4
884
885=head2 Other References
886
887Arnold, Ken and James Gosling. The Java Programming Language, 2nd
888ed. Addison-Wesley, 1998, ISBN 0-201-31006-6.
889
890Le Sergent, T. and B. Berthomieu. "Incremental MultiThreaded Garbage
891Collection on Virtually Shared Memory Architectures" in Memory
892Management: Proc. of the International Workshop IWMM 92, St. Malo,
893France, September 1992, Yves Bekkers and Jacques Cohen, eds. Springer,
8941992, ISBN 3540-55940-X (real-life thread applications).
895
896=head1 Acknowledgements
897
898Thanks (in no particular order) to Chaim Frenkel, Steve Fink, Gurusamy
899Sarathy, Ilya Zakharevich, Benjamin Sugars, Jürgen Christoffel, Joshua
900Pritikin, and Alan Burlison, for their help in reality-checking and
901polishing this article. Big thanks to Tom Christiansen for his rewrite
902of the prime number generator.
903
904=head1 AUTHOR
905
906Dan Sugalski E<lt>sugalskd@ous.eduE<gt>
907
908Slightly modified by Arthur Bergman to fit the new thread model/module.
909
910=head1 Copyrights
911
912This article originally appeared in The Perl Journal #10, and is
913copyright 1998 The Perl Journal. It appears courtesy of Jon Orwant and
914The Perl Journal. This document may be distributed under the same terms
915as Perl itself.
916
2605996a 917
53d7eaa8 918For more information please see L<threads> and L<threads::shared>.
2605996a 919