This is a live mirror of the Perl 5 development currently hosted at
Deprecate 5.005threads.
[perl5.git] / pod / perlthrtut.pod
1=head1 NAME
3perlthrtut - tutorial on threads in Perl
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
12You can see which (or neither) threading flavour you have by
13running C<perl -V> and look at the C<Platform> section.
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
20=head1 What Is A Thread Anyway?
22A thread is a flow of control through a program with a single
23execution point.
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.
31=head1 Threaded Program Models
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.
38=head2 Boss/Worker
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
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.
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.
54=head2 Work Crew
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
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
68=head2 Pipeline
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.
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
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.)
90=head1 Native threads
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
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.
101There are three basic categories of threads-user-mode threads, kernel
102threads, and multiprocessor kernel threads.
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.
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().
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.
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.
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
134Multiprocessor Kernel Threads are the final step in thread
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.
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
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.
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.
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.
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.)
165=head1 What kind of threads are perl threads?
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.
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.
184However it is important to remeber that perl threads cannot magicly
185do things unless your operating systems threads allows it. So if your
186system blocks the entire process on sleep(), so will usually perl aswell.
188=head1 Threadsafe Modules
190The addition of threads has changed Perl's internals
191substantially. There are implications for people who write
192modules with XS code or external libraries. However since the threads
193do not share data pure perl modules that don't interact with external
194systems should be safe. Modules that are not tagged as thread-safe should
195be tested or code reviewed before being used in production code.
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)
204Even if a module us threadsafe, it doesn't mean that the module is optimized
205to work well with threads. A module could maybe be rewritten to utilize the new
206features in perl threaded to increase performance in a threaded enviroment.
208If you're using a module that's not thread-safe for some reason, you
209can protect yourself by using semaphores and lots of programming
210discipline to control access to the module. Semaphores are covered
211later in the article. Perl Threads Are Different
213=head1 Thread Basics
215The core L<threads> module provides the basic functions you need to write
216threaded programs. In the following sections we'll cover the basics,
217showing you what you need to do to create a threaded program. After
218that, we'll go over some of the features of the L<threads> module that
219make threaded programming easier.
221=head2 Basic Thread Support
223Thread support is a Perl compile-time option-it's something that's
224turned on or off when Perl is built at your site, rather than when
225your programs are compiled. If your Perl wasn't compiled with thread
226support enabled, then any attempt to use threads will fail.
228Remember that the threading support in 5.005 is in beta release, and
229should be treated as such. You should expect that it may not function
230entirely properly, and the thread interface may well change some
231before it is a fully supported, production release. The beta version
232shouldn't be used for mission-critical projects. Having said that,
233threaded Perl is pretty nifty, and worth a look. (??)
235Your programs can use the Config module to check whether threads are
236enabled. If your program can't run without them, you can say something
239 $Config{useithreads} or die "Recompile Perl with threads to run this program.";
241A possibly-threaded program using a possibly-threaded module might
242have code like this:
244 use Config;
245 use MyMod;
247 if ($Config{useithreads}) {
248 # We have threads
249 require MyMod_threaded;
250 import MyMod_threaded;
251 } else {
252 require MyMod_unthreaded;
253 import MyMod_unthreaded;
254 }
256Since code that runs both with and without threads is usually pretty
257messy, it's best to isolate the thread-specific code in its own
258module. In our example above, that's what MyMod_threaded is, and it's
259only imported if we're running on a threaded Perl.
261=head2 Creating Threads
263The L<threads> package provides the tools you need to create new
264threads. Like any other module, you need to tell Perl you want to use
265it; C<use threads> imports all the pieces you need to create basic
268The simplest, straightforward way to create a thread is with new():
270 use threads;
272 $thr = threads->new(\&sub1);
274 sub sub1 {
275 print "In the thread\n";
276 }
278The new() method takes a reference to a subroutine and creates a new
279thread, which starts executing in the referenced subroutine. Control
280then passes both to the subroutine and the caller.
282If you need to, your program can pass parameters to the subroutine as
283part of the thread startup. Just include the list of parameters as
284part of the C<threads::new> call, like this:
286 use threads;
287 $Param3 = "foo";
288 $thr = threads->new(\&sub1, "Param 1", "Param 2", $Param3);
289 $thr = threads->new(\&sub1, @ParamList);
290 $thr = threads->new(\&sub1, qw(Param1 Param2 $Param3));
292 sub sub1 {
293 my @InboundParameters = @_;
294 print "In the thread\n";
295 print "got parameters >", join("<>", @InboundParameters), "<\n";
296 }
299The last example illustrates another feature of threads. You can spawn
300off several threads using the same subroutine. Each thread executes
301the same subroutine, but in a separate thread with a separate
302environment and potentially separate arguments.
304=head2 Giving up control
306There are times when you may find it useful to have a thread
307explicitly give up the CPU to another thread. Your threading package
308might not support preemptive multitasking for threads, for example, or
309you may be doing something compute-intensive and want to make sure
310that the user-interface thread gets called frequently. Regardless,
311there are times that you might want a thread to give up the processor.
313Perl's threading package provides the yield() function that does
314this. yield() is pretty straightforward, and works like this:
316 use threads;
318 sub loop {
319 my $thread = shift;
320 my $foo = 50;
321 while($foo--) { print "in thread $thread\n" }
322 threads->yield();
323 $foo = 50;
324 while($foo--) {Êprint "in thread $thread\n" }
325 }
327 my $thread1 = threads->new(\&loop, 'first');
328 my $thread2 = threads->new(\&loop, 'second');
329 my $thread3 = threads->new(\&loop, 'third');
331It is important to remember that yield() is only a hint to give up the CPU,
332it depends on your hardware, OS and threading libraries what actually happens.
333Therefore it is important to note that one should not build the scheduling of
334the threads around yield() calls. It might work on your platform but it won't
335work on another platform.
337=head2 Waiting For A Thread To Exit
339Since threads are also subroutines, they can return values. To wait
340for a thread to exit and extract any scalars it might return, you can
341use the join() method.
343 use threads;
344 $thr = threads->new(\&sub1);
346 @ReturnData = $thr->join;
347 print "Thread returned @ReturnData";
349 sub sub1 { return "Fifty-six", "foo", 2; }
351In the example above, the join() method returns as soon as the thread
352ends. In addition to waiting for a thread to finish and gathering up
353any values that the thread might have returned, join() also performs
354any OS cleanup necessary for the thread. That cleanup might be
355important, especially for long-running programs that spawn lots of
356threads. If you don't want the return values and don't want to wait
357for the thread to finish, you should call the detach() method
358instead. detach() is covered later in the article.
360=head2 Ignoring A Thread
362join() does three things: it waits for a thread to exit, cleans up
363after it, and returns any data the thread may have produced. But what
364if you're not interested in the thread's return values, and you don't
365really care when the thread finishes? All you want is for the thread
366to get cleaned up after when it's done.
368In this case, you use the detach() method. Once a thread is detached,
369it'll run until it's finished, then Perl will clean up after it
372 use threads;
373 $thr = new threads \&sub1; # Spawn the thread
375 $thr->detach; # Now we officially don't care any more
377 sub sub1 {
378 $a = 0;
379 while (1) {
380 $a++;
381 print "\$a is $a\n";
382 sleep 1;
383 }
384 }
387Once a thread is detached, it may not be joined, and any output that
388it might have produced (if it was done and waiting for a join) is
391=head1 Threads And Data
393Now that we've covered the basics of threads, it's time for our next
394topic: data. Threading introduces a couple of complications to data
395access that non-threaded programs never need to worry about.
397=head2 Shared And Unshared Data
399The biggest difference between perl threading and the old 5.005 style
400threading, or most other threading systems out there, is that all data
401is not shared. When a new perl thread is created all data is cloned
402and is private to that thread!
404To make use of threading however, one usually want the threads to share
405data between each other, that is used with the L<threads::shared> module
406and the C< : shared> attribute.
408 use threads;
409 use threads::shared;
410 my $foo : shared = 1;
411 my $bar = 1;
412 threads->new(sub { $foo++; $bar++ })->join;
414 print "$foo\n"; #prints 2 since $foo is shared
415 print "$bar\n"; #prints 1 since bar is not shared
417=head2 Thread Pitfall: Races
419While threads bring a new set of useful tools, they also bring a
420number of pitfalls. One pitfall is the race condition:
422 use threads;
423 use threads::shared;
424 my $a : shared = 1;
425 $thr1 = threads->new(\&sub1);
426 $thr2 = threads->new(\&sub2);
428 $thr1->join;
429 $thr2->join;
430 print "$a\n";
432 sub sub1 { $foo = $a; $a = $foo + 1; }
433 sub sub2 { $bar = $a; $a = $bar + 1; }
435What do you think $a will be? The answer, unfortunately, is "it
436depends." Both sub1() and sub2() access the global variable $a, once
437to read and once to write. Depending on factors ranging from your
438thread implementation's scheduling algorithm to the phase of the moon,
439$a can be 2 or 3.
441Race conditions are caused by unsynchronized access to shared
442data. Without explicit synchronization, there's no way to be sure that
443nothing has happened to the shared data between the time you access it
444and the time you update it. Even this simple code fragment has the
445possibility of error:
447 use threads;
448 my $a : shared = 2;
449 my $b : shared;
450 my $c : shared;
451 my $thr1 = threads->create(sub { $b = $a; $a = $b + 1; });
452 my $thr2 = threads->create(sub { $c = $a; $a = $c + 1; });
453 $thr1->join();
454 $thr2->join();
456Two threads both access $a. Each thread can potentially be interrupted
457at any point, or be executed in any order. At the end, $a could be 3
458or 4, and both $b and $c could be 2 or 3.
460Whenever your program accesses data or resources that can be accessed
461by other threads, you must take steps to coordinate access or risk
462data corruption and race conditions.
464=head2 Controlling access: lock()
466The lock() function takes a shared variable and puts a lock on it.
467No other thread may lock the variable until the locking thread exits
468the innermost block containing the lock.
469Using lock() is straightforward:
471 use threads;
472 my $a : shared = 4;
473 $thr1 = threads->new(sub {
474 $foo = 12;
475 {
476 lock ($a); # Block until we get access to $a
477 $b = $a;
478 $a = $b * $foo;
479 }
480 print "\$foo was $foo\n";
481 });
482 $thr2 = threads->new(sub {
483 $bar = 7;
484 {
485 lock ($a); # Block until we can get access to $a
486 $c = $a;
487 $a = $c * $bar;
488 }
489 print "\$bar was $bar\n";
490 });
491 $thr1->join;
492 $thr2->join;
493 print "\$a is $a\n";
495lock() blocks the thread until the variable being locked is
496available. When lock() returns, your thread can be sure that no other
497thread can lock that variable until the innermost block containing the
498lock exits.
500It's important to note that locks don't prevent access to the variable
501in question, only lock attempts. This is in keeping with Perl's
502longstanding tradition of courteous programming, and the advisory file
503locking that flock() gives you.
505You may lock arrays and hashes as well as scalars. Locking an array,
506though, will not block subsequent locks on array elements, just lock
507attempts on the array itself.
509Finally, locks are recursive, which means it's okay for a thread to
510lock a variable more than once. The lock will last until the outermost
511lock() on the variable goes out of scope.
513=head2 Thread Pitfall: Deadlocks
515Locks are a handy tool to synchronize access to data. Using them
516properly is the key to safe shared data. Unfortunately, locks aren't
517without their dangers. Consider the following code:
519 use threads;
520 my $a : shared = 4;
521 my $b : shared = "foo";
522 my $thr1 = threads->new(sub {
523 lock($a);
524 yield;
525 sleep 20;
526 lock ($b);
527 });
528 my $thr2 = threads->new(sub {
529 lock($b);
530 yield;
531 sleep 20;
532 lock ($a);
533 });
535This program will probably hang until you kill it. The only way it
536won't hang is if one of the two async() routines acquires both locks
537first. A guaranteed-to-hang version is more complicated, but the
538principle is the same.
540The first thread spawned by async() will grab a lock on $a then, a
541second or two later, try to grab a lock on $b. Meanwhile, the second
542thread grabs a lock on $b, then later tries to grab a lock on $a. The
543second lock attempt for both threads will block, each waiting for the
544other to release its lock.
546This condition is called a deadlock, and it occurs whenever two or
547more threads are trying to get locks on resources that the others
548own. Each thread will block, waiting for the other to release a lock
549on a resource. That never happens, though, since the thread with the
550resource is itself waiting for a lock to be released.
552There are a number of ways to handle this sort of problem. The best
553way is to always have all threads acquire locks in the exact same
554order. If, for example, you lock variables $a, $b, and $c, always lock
555$a before $b, and $b before $c. It's also best to hold on to locks for
556as short a period of time to minimize the risks of deadlock.
558=head2 Queues: Passing Data Around
560A queue is a special thread-safe object that lets you put data in one
561end and take it out the other without having to worry about
562synchronization issues. They're pretty straightforward, and look like
565 use threads;
566 use threads::shared::queue;
568 my $DataQueue = new threads::shared::queue;
569 $thr = threads->new(sub {
570 while ($DataElement = $DataQueue->dequeue) {
571 print "Popped $DataElement off the queue\n";
572 }
573 });
575 $DataQueue->enqueue(12);
576 $DataQueue->enqueue("A", "B", "C");
577 $DataQueue->enqueue(\$thr);
578 sleep 10;
579 $DataQueue->enqueue(undef);
580 $thr->join();
582You create the queue with new threads::shared::queue. Then you can add lists of
583scalars onto the end with enqueue(), and pop scalars off the front of
584it with dequeue(). A queue has no fixed size, and can grow as needed
585to hold everything pushed on to it.
587If a queue is empty, dequeue() blocks until another thread enqueues
588something. This makes queues ideal for event loops and other
589communications between threads.
592=head1 Threads And Code
594In addition to providing thread-safe access to data via locks and
595queues, threaded Perl also provides general-purpose semaphores for
596coarser synchronization than locks provide and thread-safe access to
597entire subroutines.
599=head2 Semaphores: Synchronizing Data Access
601Semaphores are a kind of generic locking mechanism. Unlike lock, which
602gets a lock on a particular scalar, Perl doesn't associate any
603particular thing with a semaphore so you can use them to control
604access to anything you like. In addition, semaphores can allow more
605than one thread to access a resource at once, though by default
606semaphores only allow one thread access at a time.
608=over 4
610=item Basic semaphores
612Semaphores have two methods, down and up. down decrements the resource
613count, while up increments it. down calls will block if the
614semaphore's current count would decrement below zero. This program
615gives a quick demonstration:
617 use threads qw(yield);
618 use threads::shared::semaphore;
619 my $semaphore = new threads::shared::semaphore;
620 $GlobalVariable = 0;
2605996a 621
622 $thr1 = new threads \&sample_sub, 1;
623 $thr2 = new threads \&sample_sub, 2;
624 $thr3 = new threads \&sample_sub, 3;
2605996a 625
626 sub sample_sub {
627 my $SubNumber = shift @_;
628 my $TryCount = 10;
629 my $LocalCopy;
630 sleep 1;
631 while ($TryCount--) {
632 $semaphore->down;
633 $LocalCopy = $GlobalVariable;
634 print "$TryCount tries left for sub $SubNumber (\$GlobalVariable is $GlobalVariable)\n";
635 yield;
636 sleep 2;
637 $LocalCopy++;
638 $GlobalVariable = $LocalCopy;
639 $semaphore->up;
640 }
641 }
643 $thr1->join();
644 $thr2->join();
645 $thr3->join();
2605996a 646
647The three invocations of the subroutine all operate in sync. The
648semaphore, though, makes sure that only one thread is accessing the
649global variable at once.
2605996a 650
c975c451 651=item Advanced Semaphores
2605996a 652
653By default, semaphores behave like locks, letting only one thread
654down() them at a time. However, there are other uses for semaphores.
2605996a 655
656Each semaphore has a counter attached to it. down() decrements the
657counter and up() increments the counter. By default, semaphores are
658created with the counter set to one, down() decrements by one, and
659up() increments by one. If down() attempts to decrement the counter
660below zero, it blocks until the counter is large enough. Note that
661while a semaphore can be created with a starting count of zero, any
662up() or down() always changes the counter by at least
663one. $semaphore->down(0) is the same as $semaphore->down(1).
2605996a 664
665The question, of course, is why would you do something like this? Why
666create a semaphore with a starting count that's not one, or why
667decrement/increment it by more than one? The answer is resource
668availability. Many resources that you want to manage access for can be
669safely used by more than one thread at once.
2605996a 670
671For example, let's take a GUI driven program. It has a semaphore that
672it uses to synchronize access to the display, so only one thread is
673ever drawing at once. Handy, but of course you don't want any thread
674to start drawing until things are properly set up. In this case, you
675can create a semaphore with a counter set to zero, and up it when
676things are ready for drawing.
2605996a 677
678Semaphores with counters greater than one are also useful for
679establishing quotas. Say, for example, that you have a number of
680threads that can do I/O at once. You don't want all the threads
681reading or writing at once though, since that can potentially swamp
682your I/O channels, or deplete your process' quota of filehandles. You
683can use a semaphore initialized to the number of concurrent I/O
684requests (or open files) that you want at any one time, and have your
685threads quietly block and unblock themselves.
2605996a 686
687Larger increments or decrements are handy in those cases where a
688thread needs to check out or return a number of resources at once.
692=head1 General Thread Utility Routines
694We've covered the workhorse parts of Perl's threading package, and
695with these tools you should be well on your way to writing threaded
696code and packages. There are a few useful little pieces that didn't
697really fit in anyplace else.
699=head2 What Thread Am I In?
701The threads->self method provides your program with a way to get an
702object representing the thread it's currently in. You can use this
703object in the same way as the ones returned from the thread creation.
705=head2 Thread IDs
707tid() is a thread object method that returns the thread ID of the
708thread the object represents. Thread IDs are integers, with the main
709thread in a program being 0. Currently Perl assigns a unique tid to
710every thread ever created in your program, assigning the first thread
711to be created a tid of 1, and increasing the tid by 1 for each new
712thread that's created.
714=head2 Are These Threads The Same?
716The equal() method takes two thread objects and returns true
717if the objects represent the same thread, and false if they don't.
719Thread objects also have an overloaded == comparison so that you can do
720comparison on them as you would with normal objects.
722=head2 What Threads Are Running?
724threads->list returns a list of thread objects, one for each thread
725that's currently running and not detached. Handy for a number of things,
726including cleaning up at the end of your program:
728 # Loop through all the threads
729 foreach $thr (threads->list) {
730 # Don't join the main thread or ourselves
731 if ($thr->tid && !threads::equal($thr, threads->self)) {
732 $thr->join;
733 }
734 }
736If not all threads are finished running when the main perl thread
737ends, perl will warn you about it and die, since it is impossible for perl
738to clean up itself while other threads are runninng
740=head1 A Complete Example
742Confused yet? It's time for an example program to show some of the
743things we've covered. This program finds prime numbers using threads.
745 1 #!/usr/bin/perl -w
746 2 # prime-pthread, courtesy of Tom Christiansen
747 3
748 4 use strict;
749 5
750 6 use threads;
751 7 use threads::shared::queue;
752 8
753 9 my $stream = new threads::shared::queue;
754 10 my $kid = new threads(\&check_num, $stream, 2);
755 11
756 12 for my $i ( 3 .. 1000 ) {
757 13 $stream->enqueue($i);
758 14 }
759 15
760 16 $stream->enqueue(undef);
761 17 $kid->join();
762 18
763 19 sub check_num {
764 20 my ($upstream, $cur_prime) = @_;
765 21 my $kid;
766 22 my $downstream = new threads::shared::queue;
767 23 while (my $num = $upstream->dequeue) {
768 24 next unless $num % $cur_prime;
769 25 if ($kid) {
770 26 $downstream->enqueue($num);
771 27 } else {
772 28 print "Found prime $num\n";
773 29 $kid = new threads(\&check_num, $downstream, $num);
774 30 }
775 31 }
776 32 $downstream->enqueue(undef) if $kid;
777 33 $kid->join() if $kid;
778 34 }
780This program uses the pipeline model to generate prime numbers. Each
781thread in the pipeline has an input queue that feeds numbers to be
782checked, a prime number that it's responsible for, and an output queue
783that it funnels numbers that have failed the check into. If the thread
784has a number that's failed its check and there's no child thread, then
785the thread must have found a new prime number. In that case, a new
786child thread is created for that prime and stuck on the end of the
789This probably sounds a bit more confusing than it really is, so lets
790go through this program piece by piece and see what it does. (For
791those of you who might be trying to remember exactly what a prime
792number is, it's a number that's only evenly divisible by itself and 1)
794The bulk of the work is done by the check_num() subroutine, which
795takes a reference to its input queue and a prime number that it's
796responsible for. After pulling in the input queue and the prime that
797the subroutine's checking (line 20), we create a new queue (line 22)
798and reserve a scalar for the thread that we're likely to create later
799(line 21).
801The while loop from lines 23 to line 31 grabs a scalar off the input
802queue and checks against the prime this thread is responsible
803for. Line 24 checks to see if there's a remainder when we modulo the
804number to be checked against our prime. If there is one, the number
805must not be evenly divisible by our prime, so we need to either pass
806it on to the next thread if we've created one (line 26) or create a
807new thread if we haven't.
809The new thread creation is line 29. We pass on to it a reference to
810the queue we've created, and the prime number we've found.
812Finally, once the loop terminates (because we got a 0 or undef in the
813queue, which serves as a note to die), we pass on the notice to our
814child and wait for it to exit if we've created a child (Lines 32 and
817Meanwhile, back in the main thread, we create a queue (line 9) and the
818initial child thread (line 10), and pre-seed it with the first prime:
8192. Then we queue all the numbers from 3 to 1000 for checking (lines
82012-14), then queue a die notice (line 16) and wait for the first child
821thread to terminate (line 17). Because a child won't die until its
822child has died, we know that we're done once we return from the join.
824That's how it works. It's pretty simple; as with many Perl programs,
825the explanation is much longer than the program.
827=head1 Conclusion
829A complete thread tutorial could fill a book (and has, many times),
830but this should get you well on your way. The final authority on how
831Perl's threads behave is the documentation bundled with the Perl
832distribution, but with what we've covered in this article, you should
833be well on your way to becoming a threaded Perl expert.
835=head1 Bibliography
837Here's a short bibliography courtesy of Jürgen Christoffel:
839=head2 Introductory Texts
841Birrell, Andrew D. An Introduction to Programming with
842Threads. Digital Equipment Corporation, 1989, DEC-SRC Research Report
843#35 online as
844 (highly
847Robbins, Kay. A., and Steven Robbins. Practical Unix Programming: A
848Guide to Concurrency, Communication, and
849Multithreading. Prentice-Hall, 1996.
851Lewis, Bill, and Daniel J. Berg. Multithreaded Programming with
852Pthreads. Prentice Hall, 1997, ISBN 0-13-443698-9 (a well-written
853introduction to threads).
855Nelson, Greg (editor). Systems Programming with Modula-3. Prentice
856Hall, 1991, ISBN 0-13-590464-1.
858Nichols, Bradford, Dick Buttlar, and Jacqueline Proulx Farrell.
859Pthreads Programming. O'Reilly & Associates, 1996, ISBN 156592-115-1
860(covers POSIX threads).
862=head2 OS-Related References
864Boykin, Joseph, David Kirschen, Alan Langerman, and Susan
865LoVerso. Programming under Mach. Addison-Wesley, 1994, ISBN
868Tanenbaum, Andrew S. Distributed Operating Systems. Prentice Hall,
8691995, ISBN 0-13-219908-4 (great textbook).
871Silberschatz, Abraham, and Peter B. Galvin. Operating System Concepts,
8724th ed. Addison-Wesley, 1995, ISBN 0-201-59292-4
874=head2 Other References
876Arnold, Ken and James Gosling. The Java Programming Language, 2nd
877ed. Addison-Wesley, 1998, ISBN 0-201-31006-6.
879Le Sergent, T. and B. Berthomieu. "Incremental MultiThreaded Garbage
880Collection on Virtually Shared Memory Architectures" in Memory
881Management: Proc. of the International Workshop IWMM 92, St. Malo,
882France, September 1992, Yves Bekkers and Jacques Cohen, eds. Springer,
8831992, ISBN 3540-55940-X (real-life thread applications).
885=head1 Acknowledgements
887Thanks (in no particular order) to Chaim Frenkel, Steve Fink, Gurusamy
888Sarathy, Ilya Zakharevich, Benjamin Sugars, Jürgen Christoffel, Joshua
889Pritikin, and Alan Burlison, for their help in reality-checking and
890polishing this article. Big thanks to Tom Christiansen for his rewrite
891of the prime number generator.
893=head1 AUTHOR
895Dan Sugalski E<lt>sugalskd@ous.eduE<gt>
897Slightly modified by Arthur Bergman to fit the new thread model/module.
899=head1 Copyrights
901This article originally appeared in The Perl Journal #10, and is
902copyright 1998 The Perl Journal. It appears courtesy of Jon Orwant and
903The Perl Journal. This document may be distributed under the same terms
904as Perl itself.
2605996a 906
53d7eaa8 907For more information please see L<threads> and L<threads::shared>.
2605996a 908