1PERLOTHRTUT(1)         Perl Programmers Reference Guide         PERLOTHRTUT(1)
2
3
4

NAME

6       perlothrtut - old tutorial on threads in Perl
7

DESCRIPTION

9       WARNING: This tutorial describes the old-style thread model that was
10       introduced in release 5.005. This model is now deprecated, and will be
11       removed, probably in version 5.10. The interfaces described here were
12       considered experimental, and are likely to be buggy.
13
14       For information about the new interpreter threads ("ithreads") model,
15       see the perlthrtut tutorial, and the threads and threads::shared mod‐
16       ules.
17
18       You are strongly encouraged to migrate any existing threads code to the
19       new model as soon as possible.
20

What Is A Thread Anyway?

22       A thread is a flow of control through a program with a single execution
23       point.
24
25       Sounds an awful lot like a process, doesn't it? Well, it should.
26       Threads are one of the pieces of a process.  Every process has at least
27       one thread and, up until now, every process running Perl had only one
28       thread.  With 5.005, though, you can create extra threads.  We're going
29       to show you how, when, and why.
30

Threaded Program Models

32       There are three basic ways that you can structure a threaded program.
33       Which model you choose depends on what you need your program to do.
34       For many non-trivial threaded programs you'll need to choose different
35       models for different pieces of your program.
36
37       Boss/Worker
38
39       The boss/worker model usually has one `boss' thread and one or more
40       `worker' threads.  The boss thread gathers or generates tasks that need
41       to be done, then parcels those tasks out to the appropriate worker
42       thread.
43
44       This model is common in GUI and server programs, where a main thread
45       waits for some event and then passes that event to the appropriate
46       worker threads for processing.  Once the event has been passed on, the
47       boss thread goes back to waiting for another event.
48
49       The boss thread does relatively little work.  While tasks aren't neces‐
50       sarily performed faster than with any other method, it tends to have
51       the best user-response times.
52
53       Work Crew
54
55       In the work crew model, several threads are created that do essentially
56       the same thing to different pieces of data.  It closely mirrors classi‐
57       cal parallel processing and vector processors, where a large array of
58       processors do the exact same thing to many pieces of data.
59
60       This model is particularly useful if the system running the program
61       will distribute multiple threads across different processors.  It can
62       also be useful in ray tracing or rendering engines, where the individ‐
63       ual threads can pass on interim results to give the user visual feed‐
64       back.
65
66       Pipeline
67
68       The pipeline model divides up a task into a series of steps, and passes
69       the results of one step on to the thread processing the next.  Each
70       thread does one thing to each piece of data and passes the results to
71       the next thread in line.
72
73       This model makes the most sense if you have multiple processors so two
74       or more threads will be executing in parallel, though it can often make
75       sense in other contexts as well.  It tends to keep the individual tasks
76       small and simple, as well as allowing some parts of the pipeline to
77       block (on I/O or system calls, for example) while other parts keep
78       going.  If you're running different parts of the pipeline on different
79       processors you may also take advantage of the caches on each processor.
80
81       This model is also handy for a form of recursive programming where,
82       rather than having a subroutine call itself, it instead creates another
83       thread.  Prime and Fibonacci generators both map well to this form of
84       the pipeline model. (A version of a prime number generator is presented
85       later on.)
86

Native threads

88       There are several different ways to implement threads on a system.  How
89       threads are implemented depends both on the vendor and, in some cases,
90       the version of the operating system.  Often the first implementation
91       will be relatively simple, but later versions of the OS will be more
92       sophisticated.
93
94       While the information in this section is useful, it's not necessary, so
95       you can skip it if you don't feel up to it.
96
97       There are three basic categories of threads-user-mode threads, kernel
98       threads, and multiprocessor kernel threads.
99
100       User-mode threads are threads that live entirely within a program and
101       its libraries.  In this model, the OS knows nothing about threads.  As
102       far as it's concerned, your process is just a process.
103
104       This is the easiest way to implement threads, and the way most OSes
105       start.  The big disadvantage is that, since the OS knows nothing about
106       threads, if one thread blocks they all do.  Typical blocking activities
107       include most system calls, most I/O, and things like sleep().
108
109       Kernel threads are the next step in thread evolution.  The OS knows
110       about kernel threads, and makes allowances for them.  The main differ‐
111       ence between a kernel thread and a user-mode thread is blocking.  With
112       kernel threads, things that block a single thread don't block other
113       threads.  This is not the case with user-mode threads, where the kernel
114       blocks at the process level and not the thread level.
115
116       This is a big step forward, and can give a threaded program quite a
117       performance boost over non-threaded programs.  Threads that block per‐
118       forming I/O, for example, won't block threads that are doing other
119       things.  Each process still has only one thread running at once,
120       though, regardless of how many CPUs a system might have.
121
122       Since kernel threading can interrupt a thread at any time, they will
123       uncover some of the implicit locking assumptions you may make in your
124       program.  For example, something as simple as "$a = $a + 2" can behave
125       unpredictably with kernel threads if $a is visible to other threads, as
126       another thread may have changed $a between the time it was fetched on
127       the right hand side and the time the new value is stored.
128
129       Multiprocessor Kernel Threads are the final step in thread support.
130       With multiprocessor kernel threads on a machine with multiple CPUs, the
131       OS may schedule two or more threads to run simultaneously on different
132       CPUs.
133
134       This can give a serious performance boost to your threaded program,
135       since more than one thread will be executing at the same time.  As a
136       tradeoff, though, any of those nagging synchronization issues that
137       might not have shown with basic kernel threads will appear with a
138       vengeance.
139
140       In addition to the different levels of OS involvement in threads, dif‐
141       ferent OSes (and different thread implementations for a particular OS)
142       allocate CPU cycles to threads in different ways.
143
144       Cooperative multitasking systems have running threads give up control
145       if one of two things happen.  If a thread calls a yield function, it
146       gives up control.  It also gives up control if the thread does some‐
147       thing that would cause it to block, such as perform I/O.  In a coopera‐
148       tive multitasking implementation, one thread can starve all the others
149       for CPU time if it so chooses.
150
151       Preemptive multitasking systems interrupt threads at regular intervals
152       while the system decides which thread should run next.  In a preemptive
153       multitasking system, one thread usually won't monopolize the CPU.
154
155       On some systems, there can be cooperative and preemptive threads run‐
156       ning simultaneously. (Threads running with realtime priorities often
157       behave cooperatively, for example, while threads running at normal pri‐
158       orities behave preemptively.)
159

What kind of threads are perl threads?

161       If you have experience with other thread implementations, you might
162       find that things aren't quite what you expect.  It's very important to
163       remember when dealing with Perl threads that Perl Threads Are Not X
164       Threads, for all values of X.  They aren't POSIX threads, or Dec‐
165       Threads, or Java's Green threads, or Win32 threads.  There are similar‐
166       ities, and the broad concepts are the same, but if you start looking
167       for implementation details you're going to be either disappointed or
168       confused.  Possibly both.
169
170       This is not to say that Perl threads are completely different from
171       everything that's ever come before--they're not.  Perl's threading
172       model owes a lot to other thread models, especially POSIX.  Just as
173       Perl is not C, though, Perl threads are not POSIX threads.  So if you
174       find yourself looking for mutexes, or thread priorities, it's time to
175       step back a bit and think about what you want to do and how Perl can do
176       it.
177

Threadsafe Modules

179       The addition of threads has changed Perl's internals substantially.
180       There are implications for people who write modules--especially modules
181       with XS code or external libraries.  While most modules won't encounter
182       any problems, modules that aren't explicitly tagged as thread-safe
183       should be tested before being used in production code.
184
185       Not all modules that you might use are thread-safe, and you should
186       always assume a module is unsafe unless the documentation says other‐
187       wise.  This includes modules that are distributed as part of the core.
188       Threads are a beta feature, and even some of the standard modules
189       aren't thread-safe.
190
191       If you're using a module that's not thread-safe for some reason, you
192       can protect yourself by using semaphores and lots of programming disci‐
193       pline to control access to the module.  Semaphores are covered later in
194       the article.  Perl Threads Are Different
195

Thread Basics

197       The core Thread module provides the basic functions you need to write
198       threaded programs.  In the following sections we'll cover the basics,
199       showing you what you need to do to create a threaded program.   After
200       that, we'll go over some of the features of the Thread module that make
201       threaded programming easier.
202
203       Basic Thread Support
204
205       Thread support is a Perl compile-time option-it's something that's
206       turned on or off when Perl is built at your site, rather than when your
207       programs are compiled. If your Perl wasn't compiled with thread support
208       enabled, then any attempt to use threads will fail.
209
210       Remember that the threading support in 5.005 is in beta release, and
211       should be treated as such.   You should expect that it may not function
212       entirely properly, and the thread interface may well change some before
213       it is a fully supported, production release.  The beta version
214       shouldn't be used for mission-critical projects.  Having said that,
215       threaded Perl is pretty nifty, and worth a look.
216
217       Your programs can use the Config module to check whether threads are
218       enabled. If your program can't run without them, you can say something
219       like:
220
221         $Config{usethreads} or die "Recompile Perl with threads to run this program.";
222
223       A possibly-threaded program using a possibly-threaded module might have
224       code like this:
225
226           use Config;
227           use MyMod;
228
229           if ($Config{usethreads}) {
230               # We have threads
231               require MyMod_threaded;
232               import MyMod_threaded;
233           } else {
234               require MyMod_unthreaded;
235               import MyMod_unthreaded;
236           }
237
238       Since code that runs both with and without threads is usually pretty
239       messy, it's best to isolate the thread-specific code in its own module.
240       In our example above, that's what MyMod_threaded is, and it's only
241       imported if we're running on a threaded Perl.
242
243       Creating Threads
244
245       The Thread package provides the tools you need to create new threads.
246       Like any other module, you need to tell Perl you want to use it; use
247       Thread imports all the pieces you need to create basic threads.
248
249       The simplest, straightforward way to create a thread is with new():
250
251           use Thread;
252
253           $thr = new Thread \&sub1;
254
255           sub sub1 {
256               print "In the thread\n";
257           }
258
259       The new() method takes a reference to a subroutine and creates a new
260       thread, which starts executing in the referenced subroutine.  Control
261       then passes both to the subroutine and the caller.
262
263       If you need to, your program can pass parameters to the subroutine as
264       part of the thread startup.  Just include the list of parameters as
265       part of the "Thread::new" call, like this:
266
267           use Thread;
268           $Param3 = "foo";
269           $thr = new Thread \&sub1, "Param 1", "Param 2", $Param3;
270           $thr = new Thread \&sub1, @ParamList;
271           $thr = new Thread \&sub1, qw(Param1 Param2 $Param3);
272
273           sub sub1 {
274               my @InboundParameters = @_;
275               print "In the thread\n";
276               print "got parameters >", join("<>", @InboundParameters), "<\n";
277           }
278
279       The subroutine runs like a normal Perl subroutine, and the call to new
280       Thread returns whatever the subroutine returns.
281
282       The last example illustrates another feature of threads.  You can spawn
283       off several threads using the same subroutine.  Each thread executes
284       the same subroutine, but in a separate thread with a separate environ‐
285       ment and potentially separate arguments.
286
287       The other way to spawn a new thread is with async(), which is a way to
288       spin off a chunk of code like eval(), but into its own thread:
289
290           use Thread qw(async);
291
292           $LineCount = 0;
293
294           $thr = async {
295               while(<>) {$LineCount++}
296               print "Got $LineCount lines\n";
297           };
298
299           print "Waiting for the linecount to end\n";
300           $thr->join;
301           print "All done\n";
302
303       You'll notice we did a use Thread qw(async) in that example.  async is
304       not exported by default, so if you want it, you'll either need to
305       import it before you use it or fully qualify it as Thread::async.
306       You'll also note that there's a semicolon after the closing brace.
307       That's because async() treats the following block as an anonymous sub‐
308       routine, so the semicolon is necessary.
309
310       Like eval(), the code executes in the same context as it would if it
311       weren't spun off.  Since both the code inside and after the async start
312       executing, you need to be careful with any shared resources.  Locking
313       and other synchronization techniques are covered later.
314
315       Giving up control
316
317       There are times when you may find it useful to have a thread explicitly
318       give up the CPU to another thread.  Your threading package might not
319       support preemptive multitasking for threads, for example, or you may be
320       doing something compute-intensive and want to make sure that the user-
321       interface thread gets called frequently.  Regardless, there are times
322       that you might want a thread to give up the processor.
323
324       Perl's threading package provides the yield() function that does this.
325       yield() is pretty straightforward, and works like this:
326
327           use Thread qw(yield async);
328           async {
329               my $foo = 50;
330               while ($foo--) { print "first async\n" }
331               yield;
332               $foo = 50;
333               while ($foo--) { print "first async\n" }
334           };
335           async {
336               my $foo = 50;
337               while ($foo--) { print "second async\n" }
338               yield;
339               $foo = 50;
340               while ($foo--) { print "second async\n" }
341           };
342
343       Waiting For A Thread To Exit
344
345       Since threads are also subroutines, they can return values.  To wait
346       for a thread to exit and extract any scalars it might return, you can
347       use the join() method.
348
349           use Thread;
350           $thr = new Thread \&sub1;
351
352           @ReturnData = $thr->join;
353           print "Thread returned @ReturnData";
354
355           sub sub1 { return "Fifty-six", "foo", 2; }
356
357       In the example above, the join() method returns as soon as the thread
358       ends.  In addition to waiting for a thread to finish and gathering up
359       any values that the thread might have returned, join() also performs
360       any OS cleanup necessary for the thread.  That cleanup might be impor‐
361       tant, especially for long-running programs that spawn lots of threads.
362       If you don't want the return values and don't want to wait for the
363       thread to finish, you should call the detach() method instead. detach()
364       is covered later in the article.
365
366       Errors In Threads
367
368       So what happens when an error occurs in a thread? Any errors that could
369       be caught with eval() are postponed until the thread is joined.  If
370       your program never joins, the errors appear when your program exits.
371
372       Errors deferred until a join() can be caught with eval():
373
374           use Thread qw(async);
375           $thr = async {$b = 3/0};   # Divide by zero error
376           $foo = eval {$thr->join};
377           if ($@) {
378               print "died with error $@\n";
379           } else {
380               print "Hey, why aren't you dead?\n";
381           }
382
383       eval() passes any results from the joined thread back unmodified, so if
384       you want the return value of the thread, this is your only chance to
385       get them.
386
387       Ignoring A Thread
388
389       join() does three things: it waits for a thread to exit, cleans up
390       after it, and returns any data the thread may have produced.  But what
391       if you're not interested in the thread's return values, and you don't
392       really care when the thread finishes? All you want is for the thread to
393       get cleaned up after when it's done.
394
395       In this case, you use the detach() method.  Once a thread is detached,
396       it'll run until it's finished, then Perl will clean up after it auto‐
397       matically.
398
399           use Thread;
400           $thr = new Thread \&sub1; # Spawn the thread
401
402           $thr->detach; # Now we officially don't care any more
403
404           sub sub1 {
405               $a = 0;
406               while (1) {
407                   $a++;
408                   print "\$a is $a\n";
409                   sleep 1;
410               }
411           }
412
413       Once a thread is detached, it may not be joined, and any output that it
414       might have produced (if it was done and waiting for a join) is lost.
415

Threads And Data

417       Now that we've covered the basics of threads, it's time for our next
418       topic: data.  Threading introduces a couple of complications to data
419       access that non-threaded programs never need to worry about.
420
421       Shared And Unshared Data
422
423       The single most important thing to remember when using threads is that
424       all threads potentially have access to all the data anywhere in your
425       program.  While this is true with a nonthreaded Perl program as well,
426       it's especially important to remember with a threaded program, since
427       more than one thread can be accessing this data at once.
428
429       Perl's scoping rules don't change because you're using threads.  If a
430       subroutine (or block, in the case of async()) could see a variable if
431       you weren't running with threads, it can see it if you are.  This is
432       especially important for the subroutines that create, and makes "my"
433       variables even more important.  Remember--if your variables aren't lex‐
434       ically scoped (declared with "my") you're probably sharing them between
435       threads.
436
437       Thread Pitfall: Races
438
439       While threads bring a new set of useful tools, they also bring a number
440       of pitfalls.  One pitfall is the race condition:
441
442           use Thread;
443           $a = 1;
444           $thr1 = Thread->new(\&sub1);
445           $thr2 = Thread->new(\&sub2);
446
447           sleep 10;
448           print "$a\n";
449
450           sub sub1 { $foo = $a; $a = $foo + 1; }
451           sub sub2 { $bar = $a; $a = $bar + 1; }
452
453       What do you think $a will be? The answer, unfortunately, is "it
454       depends." Both sub1() and sub2() access the global variable $a, once to
455       read and once to write.  Depending on factors ranging from your thread
456       implementation's scheduling algorithm to the phase of the moon, $a can
457       be 2 or 3.
458
459       Race conditions are caused by unsynchronized access to shared data.
460       Without explicit synchronization, there's no way to be sure that noth‐
461       ing has happened to the shared data between the time you access it and
462       the time you update it.  Even this simple code fragment has the possi‐
463       bility of error:
464
465           use Thread qw(async);
466           $a = 2;
467           async{ $b = $a; $a = $b + 1; };
468           async{ $c = $a; $a = $c + 1; };
469
470       Two threads both access $a.  Each thread can potentially be interrupted
471       at any point, or be executed in any order.  At the end, $a could be 3
472       or 4, and both $b and $c could be 2 or 3.
473
474       Whenever your program accesses data or resources that can be accessed
475       by other threads, you must take steps to coordinate access or risk data
476       corruption and race conditions.
477
478       Controlling access: lock()
479
480       The lock() function takes a variable (or subroutine, but we'll get to
481       that later) and puts a lock on it.  No other thread may lock the vari‐
482       able until the locking thread exits the innermost block containing the
483       lock.  Using lock() is straightforward:
484
485           use Thread qw(async);
486           $a = 4;
487           $thr1 = async {
488               $foo = 12;
489               {
490                   lock ($a); # Block until we get access to $a
491                   $b = $a;
492                   $a = $b * $foo;
493               }
494               print "\$foo was $foo\n";
495           };
496           $thr2 = async {
497               $bar = 7;
498               {
499                   lock ($a); # Block until we can get access to $a
500                   $c = $a;
501                   $a = $c * $bar;
502               }
503               print "\$bar was $bar\n";
504           };
505           $thr1->join;
506           $thr2->join;
507           print "\$a is $a\n";
508
509       lock() blocks the thread until the variable being locked is available.
510       When lock() returns, your thread can be sure that no other thread can
511       lock that variable until the innermost block containing the lock exits.
512
513       It's important to note that locks don't prevent access to the variable
514       in question, only lock attempts.  This is in keeping with Perl's long‐
515       standing tradition of courteous programming, and the advisory file
516       locking that flock() gives you.  Locked subroutines behave differently,
517       however.  We'll cover that later in the article.
518
519       You may lock arrays and hashes as well as scalars.  Locking an array,
520       though, will not block subsequent locks on array elements, just lock
521       attempts on the array itself.
522
523       Finally, locks are recursive, which means it's okay for a thread to
524       lock a variable more than once.  The lock will last until the outermost
525       lock() on the variable goes out of scope.
526
527       Thread Pitfall: Deadlocks
528
529       Locks are a handy tool to synchronize access to data.  Using them prop‐
530       erly is the key to safe shared data.  Unfortunately, locks aren't with‐
531       out their dangers.  Consider the following code:
532
533           use Thread qw(async yield);
534           $a = 4;
535           $b = "foo";
536           async {
537               lock($a);
538               yield;
539               sleep 20;
540               lock ($b);
541           };
542           async {
543               lock($b);
544               yield;
545               sleep 20;
546               lock ($a);
547           };
548
549       This program will probably hang until you kill it.  The only way it
550       won't hang is if one of the two async() routines acquires both locks
551       first.  A guaranteed-to-hang version is more complicated, but the prin‐
552       ciple is the same.
553
554       The first thread spawned by async() will grab a lock on $a then, a sec‐
555       ond or two later, try to grab a lock on $b.  Meanwhile, the second
556       thread grabs a lock on $b, then later tries to grab a lock on $a.  The
557       second lock attempt for both threads will block, each waiting for the
558       other to release its lock.
559
560       This condition is called a deadlock, and it occurs whenever two or more
561       threads are trying to get locks on resources that the others own.  Each
562       thread will block, waiting for the other to release a lock on a
563       resource.  That never happens, though, since the thread with the
564       resource is itself waiting for a lock to be released.
565
566       There are a number of ways to handle this sort of problem.  The best
567       way is to always have all threads acquire locks in the exact same
568       order.  If, for example, you lock variables $a, $b, and $c, always lock
569       $a before $b, and $b before $c.  It's also best to hold on to locks for
570       as short a period of time to minimize the risks of deadlock.
571
572       Queues: Passing Data Around
573
574       A queue is a special thread-safe object that lets you put data in one
575       end and take it out the other without having to worry about synchro‐
576       nization issues.  They're pretty straightforward, and look like this:
577
578           use Thread qw(async);
579           use Thread::Queue;
580
581           my $DataQueue = new Thread::Queue;
582           $thr = async {
583               while ($DataElement = $DataQueue->dequeue) {
584                   print "Popped $DataElement off the queue\n";
585               }
586           };
587
588           $DataQueue->enqueue(12);
589           $DataQueue->enqueue("A", "B", "C");
590           $DataQueue->enqueue(\$thr);
591           sleep 10;
592           $DataQueue->enqueue(undef);
593
594       You create the queue with new Thread::Queue.  Then you can add lists of
595       scalars onto the end with enqueue(), and pop scalars off the front of
596       it with dequeue().  A queue has no fixed size, and can grow as needed
597       to hold everything pushed on to it.
598
599       If a queue is empty, dequeue() blocks until another thread enqueues
600       something.  This makes queues ideal for event loops and other communi‐
601       cations between threads.
602

Threads And Code

604       In addition to providing thread-safe access to data via locks and
605       queues, threaded Perl also provides general-purpose semaphores for
606       coarser synchronization than locks provide and thread-safe access to
607       entire subroutines.
608
609       Semaphores: Synchronizing Data Access
610
611       Semaphores are a kind of generic locking mechanism.  Unlike lock, which
612       gets a lock on a particular scalar, Perl doesn't associate any particu‐
613       lar thing with a semaphore so you can use them to control access to
614       anything you like.  In addition, semaphores can allow more than one
615       thread to access a resource at once, though by default semaphores only
616       allow one thread access at a time.
617
618       Basic semaphores
619           Semaphores have two methods, down and up. down decrements the
620           resource count, while up increments it.  down calls will block if
621           the semaphore's current count would decrement below zero.  This
622           program gives a quick demonstration:
623
624               use Thread qw(yield);
625               use Thread::Semaphore;
626               my $semaphore = new Thread::Semaphore;
627               $GlobalVariable = 0;
628
629               $thr1 = new Thread \&sample_sub, 1;
630               $thr2 = new Thread \&sample_sub, 2;
631               $thr3 = new Thread \&sample_sub, 3;
632
633               sub sample_sub {
634                   my $SubNumber = shift @_;
635                   my $TryCount = 10;
636                   my $LocalCopy;
637                   sleep 1;
638                   while ($TryCount--) {
639                       $semaphore->down;
640                       $LocalCopy = $GlobalVariable;
641                       print "$TryCount tries left for sub $SubNumber (\$GlobalVariable is $GlobalVariable)\n";
642                       yield;
643                       sleep 2;
644                       $LocalCopy++;
645                       $GlobalVariable = $LocalCopy;
646                       $semaphore->up;
647                   }
648               }
649
650           The three invocations of the subroutine all operate in sync.  The
651           semaphore, though, makes sure that only one thread is accessing the
652           global variable at once.
653
654       Advanced Semaphores
655           By default, semaphores behave like locks, letting only one thread
656           down() them at a time.  However, there are other uses for sema‐
657           phores.
658
659           Each semaphore has a counter attached to it. down() decrements the
660           counter and up() increments the counter.  By default, semaphores
661           are created with the counter set to one, down() decrements by one,
662           and up() increments by one.  If down() attempts to decrement the
663           counter below zero, it blocks until the counter is large enough.
664           Note that while a semaphore can be created with a starting count of
665           zero, any up() or down() always changes the counter by at least
666           one. $semaphore->down(0) is the same as $semaphore->down(1).
667
668           The question, of course, is why would you do something like this?
669           Why create a semaphore with a starting count that's not one, or why
670           decrement/increment it by more than one? The answer is resource
671           availability.  Many resources that you want to manage access for
672           can be safely used by more than one thread at once.
673
674           For example, let's take a GUI driven program.  It has a semaphore
675           that it uses to synchronize access to the display, so only one
676           thread is ever drawing at once.  Handy, but of course you don't
677           want any thread to start drawing until things are properly set up.
678           In this case, you can create a semaphore with a counter set to
679           zero, and up it when things are ready for drawing.
680
681           Semaphores with counters greater than one are also useful for
682           establishing quotas.  Say, for example, that you have a number of
683           threads that can do I/O at once.  You don't want all the threads
684           reading or writing at once though, since that can potentially swamp
685           your I/O channels, or deplete your process' quota of filehandles.
686           You can use a semaphore initialized to the number of concurrent I/O
687           requests (or open files) that you want at any one time, and have
688           your threads quietly block and unblock themselves.
689
690           Larger increments or decrements are handy in those cases where a
691           thread needs to check out or return a number of resources at once.
692
693       Attributes: Restricting Access To Subroutines
694
695       In addition to synchronizing access to data or resources, you might
696       find it useful to synchronize access to subroutines.  You may be
697       accessing a singular machine resource (perhaps a vector processor), or
698       find it easier to serialize calls to a particular subroutine than to
699       have a set of locks and semaphores.
700
701       One of the additions to Perl 5.005 is subroutine attributes.  The
702       Thread package uses these to provide several flavors of serialization.
703       It's important to remember that these attributes are used in the compi‐
704       lation phase of your program so you can't change a subroutine's behav‐
705       ior while your program is actually running.
706
707       Subroutine Locks
708
709       The basic subroutine lock looks like this:
710
711           sub test_sub :locked {
712           }
713
714       This ensures that only one thread will be executing this subroutine at
715       any one time.  Once a thread calls this subroutine, any other thread
716       that calls it will block until the thread in the subroutine exits it.
717       A more elaborate example looks like this:
718
719           use Thread qw(yield);
720
721           new Thread \&thread_sub, 1;
722           new Thread \&thread_sub, 2;
723           new Thread \&thread_sub, 3;
724           new Thread \&thread_sub, 4;
725
726           sub sync_sub :locked {
727               my $CallingThread = shift @_;
728               print "In sync_sub for thread $CallingThread\n";
729               yield;
730               sleep 3;
731               print "Leaving sync_sub for thread $CallingThread\n";
732           }
733
734           sub thread_sub {
735               my $ThreadID = shift @_;
736               print "Thread $ThreadID calling sync_sub\n";
737               sync_sub($ThreadID);
738               print "$ThreadID is done with sync_sub\n";
739           }
740
741       The "locked" attribute tells perl to lock sync_sub(), and if you run
742       this, you can see that only one thread is in it at any one time.
743
744       Methods
745
746       Locking an entire subroutine can sometimes be overkill, especially when
747       dealing with Perl objects.  When calling a method for an object, for
748       example, you want to serialize calls to a method, so that only one
749       thread will be in the subroutine for a particular object, but threads
750       calling that subroutine for a different object aren't blocked.  The
751       method attribute indicates whether the subroutine is really a method.
752
753           use Thread;
754
755           sub tester {
756               my $thrnum = shift @_;
757               my $bar = new Foo;
758               foreach (1..10) {
759                   print "$thrnum calling per_object\n";
760                   $bar->per_object($thrnum);
761                   print "$thrnum out of per_object\n";
762                   yield;
763                   print "$thrnum calling one_at_a_time\n";
764                   $bar->one_at_a_time($thrnum);
765                   print "$thrnum out of one_at_a_time\n";
766                   yield;
767               }
768           }
769
770           foreach my $thrnum (1..10) {
771               new Thread \&tester, $thrnum;
772           }
773
774           package Foo;
775           sub new {
776               my $class = shift @_;
777               return bless [@_], $class;
778           }
779
780           sub per_object :locked :method {
781               my ($class, $thrnum) = @_;
782               print "In per_object for thread $thrnum\n";
783               yield;
784               sleep 2;
785               print "Exiting per_object for thread $thrnum\n";
786           }
787
788           sub one_at_a_time :locked {
789               my ($class, $thrnum) = @_;
790               print "In one_at_a_time for thread $thrnum\n";
791               yield;
792               sleep 2;
793               print "Exiting one_at_a_time for thread $thrnum\n";
794           }
795
796       As you can see from the output (omitted for brevity; it's 800 lines)
797       all the threads can be in per_object() simultaneously, but only one
798       thread is ever in one_at_a_time() at once.
799
800       Locking A Subroutine
801
802       You can lock a subroutine as you would lock a variable.  Subroutine
803       locks work the same as specifying a "locked" attribute for the subrou‐
804       tine, and block all access to the subroutine for other threads until
805       the lock goes out of scope.  When the subroutine isn't locked, any num‐
806       ber of threads can be in it at once, and getting a lock on a subroutine
807       doesn't affect threads already in the subroutine.  Getting a lock on a
808       subroutine looks like this:
809
810           lock(\&sub_to_lock);
811
812       Simple enough.  Unlike the "locked" attribute, which is a compile time
813       option, locking and unlocking a subroutine can be done at runtime at
814       your discretion.  There is some runtime penalty to using lock(\&sub)
815       instead of the "locked" attribute, so make sure you're choosing the
816       proper method to do the locking.
817
818       You'd choose lock(\&sub) when writing modules and code to run on both
819       threaded and unthreaded Perl, especially for code that will run on
820       5.004 or earlier Perls.  In that case, it's useful to have subroutines
821       that should be serialized lock themselves if they're running threaded,
822       like so:
823
824           package Foo;
825           use Config;
826           $Running_Threaded = 0;
827
828           BEGIN { $Running_Threaded = $Config{'usethreads'} }
829
830           sub sub1 { lock(\&sub1) if $Running_Threaded }
831
832       This way you can ensure single-threadedness regardless of which version
833       of Perl you're running.
834

General Thread Utility Routines

836       We've covered the workhorse parts of Perl's threading package, and with
837       these tools you should be well on your way to writing threaded code and
838       packages.  There are a few useful little pieces that didn't really fit
839       in anyplace else.
840
841       What Thread Am I In?
842
843       The Thread->self method provides your program with a way to get an
844       object representing the thread it's currently in.  You can use this
845       object in the same way as the ones returned from the thread creation.
846
847       Thread IDs
848
849       tid() is a thread object method that returns the thread ID of the
850       thread the object represents.  Thread IDs are integers, with the main
851       thread in a program being 0.  Currently Perl assigns a unique tid to
852       every thread ever created in your program, assigning the first thread
853       to be created a tid of 1, and increasing the tid by 1 for each new
854       thread that's created.
855
856       Are These Threads The Same?
857
858       The equal() method takes two thread objects and returns true if the
859       objects represent the same thread, and false if they don't.
860
861       What Threads Are Running?
862
863       Thread->list returns a list of thread objects, one for each thread
864       that's currently running.  Handy for a number of things, including
865       cleaning up at the end of your program:
866
867           # Loop through all the threads
868           foreach $thr (Thread->list) {
869               # Don't join the main thread or ourselves
870               if ($thr->tid && !Thread::equal($thr, Thread->self)) {
871                   $thr->join;
872               }
873           }
874
875       The example above is just for illustration.  It isn't strictly neces‐
876       sary to join all the threads you create, since Perl detaches all the
877       threads before it exits.
878

A Complete Example

880       Confused yet? It's time for an example program to show some of the
881       things we've covered.  This program finds prime numbers using threads.
882
883           1  #!/usr/bin/perl -w
884           2  # prime-pthread, courtesy of Tom Christiansen
885           3
886           4  use strict;
887           5
888           6  use Thread;
889           7  use Thread::Queue;
890           8
891           9  my $stream = new Thread::Queue;
892           10 my $kid    = new Thread(\&check_num, $stream, 2);
893           11
894           12 for my $i ( 3 .. 1000 ) {
895           13     $stream->enqueue($i);
896           14 }
897           15
898           16 $stream->enqueue(undef);
899           17 $kid->join();
900           18
901           19 sub check_num {
902           20     my ($upstream, $cur_prime) = @_;
903           21     my $kid;
904           22     my $downstream = new Thread::Queue;
905           23     while (my $num = $upstream->dequeue) {
906           24         next unless $num % $cur_prime;
907           25         if ($kid) {
908           26            $downstream->enqueue($num);
909           27                  } else {
910           28            print "Found prime $num\n";
911           29                $kid = new Thread(\&check_num, $downstream, $num);
912           30         }
913           31     }
914           32     $downstream->enqueue(undef) if $kid;
915           33     $kid->join()         if $kid;
916           34 }
917
918       This program uses the pipeline model to generate prime numbers.  Each
919       thread in the pipeline has an input queue that feeds numbers to be
920       checked, a prime number that it's responsible for, and an output queue
921       that it funnels numbers that have failed the check into.  If the thread
922       has a number that's failed its check and there's no child thread, then
923       the thread must have found a new prime number.  In that case, a new
924       child thread is created for that prime and stuck on the end of the
925       pipeline.
926
927       This probably sounds a bit more confusing than it really is, so lets go
928       through this program piece by piece and see what it does.  (For those
929       of you who might be trying to remember exactly what a prime number is,
930       it's a number that's only evenly divisible by itself and 1)
931
932       The bulk of the work is done by the check_num() subroutine, which takes
933       a reference to its input queue and a prime number that it's responsible
934       for.  After pulling in the input queue and the prime that the subrou‐
935       tine's checking (line 20), we create a new queue (line 22) and reserve
936       a scalar for the thread that we're likely to create later (line 21).
937
938       The while loop from lines 23 to line 31 grabs a scalar off the input
939       queue and checks against the prime this thread is responsible for.
940       Line 24 checks to see if there's a remainder when we modulo the number
941       to be checked against our prime.  If there is one, the number must not
942       be evenly divisible by our prime, so we need to either pass it on to
943       the next thread if we've created one (line 26) or create a new thread
944       if we haven't.
945
946       The new thread creation is line 29.  We pass on to it a reference to
947       the queue we've created, and the prime number we've found.
948
949       Finally, once the loop terminates (because we got a 0 or undef in the
950       queue, which serves as a note to die), we pass on the notice to our
951       child and wait for it to exit if we've created a child (Lines 32 and
952       37).
953
954       Meanwhile, back in the main thread, we create a queue (line 9) and the
955       initial child thread (line 10), and pre-seed it with the first prime:
956       2.  Then we queue all the numbers from 3 to 1000 for checking (lines
957       12-14), then queue a die notice (line 16) and wait for the first child
958       thread to terminate (line 17).  Because a child won't die until its
959       child has died, we know that we're done once we return from the join.
960
961       That's how it works.  It's pretty simple; as with many Perl programs,
962       the explanation is much longer than the program.
963

Conclusion

965       A complete thread tutorial could fill a book (and has, many times), but
966       this should get you well on your way.  The final authority on how
967       Perl's threads behave is the documentation bundled with the Perl dis‐
968       tribution, but with what we've covered in this article, you should be
969       well on your way to becoming a threaded Perl expert.
970

Bibliography

972       Here's a short bibliography courtesy of Jürgen Christoffel:
973
974       Introductory Texts
975
976       Birrell, Andrew D. An Introduction to Programming with Threads. Digital
977       Equipment Corporation, 1989, DEC-SRC Research Report #35 online as
978       http://www.research.digital.com/SRC/staff/birrell/bib.html (highly rec‐
979       ommended)
980
981       Robbins, Kay. A., and Steven Robbins. Practical Unix Programming: A
982       Guide to Concurrency, Communication, and Multithreading. Prentice-Hall,
983       1996.
984
985       Lewis, Bill, and Daniel J. Berg. Multithreaded Programming with
986       Pthreads. Prentice Hall, 1997, ISBN 0-13-443698-9 (a well-written
987       introduction to threads).
988
989       Nelson, Greg (editor). Systems Programming with Modula-3.  Prentice
990       Hall, 1991, ISBN 0-13-590464-1.
991
992       Nichols, Bradford, Dick Buttlar, and Jacqueline Proulx Farrell.
993       Pthreads Programming. O'Reilly & Associates, 1996, ISBN 156592-115-1
994       (covers POSIX threads).
995
996       OS-Related References
997
998       Boykin, Joseph, David Kirschen, Alan Langerman, and Susan LoVerso. Pro‐
999       gramming under Mach. Addison-Wesley, 1994, ISBN 0-201-52739-1.
1000
1001       Tanenbaum, Andrew S. Distributed Operating Systems. Prentice Hall,
1002       1995, ISBN 0-13-219908-4 (great textbook).
1003
1004       Silberschatz, Abraham, and Peter B. Galvin. Operating System Concepts,
1005       4th ed. Addison-Wesley, 1995, ISBN 0-201-59292-4
1006
1007       Other References
1008
1009       Arnold, Ken and James Gosling. The Java Programming Language, 2nd ed.
1010       Addison-Wesley, 1998, ISBN 0-201-31006-6.
1011
1012       Le Sergent, T. and B. Berthomieu. "Incremental MultiThreaded Garbage
1013       Collection on Virtually Shared Memory Architectures" in Memory Manage‐
1014       ment: Proc. of the International Workshop IWMM 92, St. Malo, France,
1015       September 1992, Yves Bekkers and Jacques Cohen, eds. Springer, 1992,
1016       ISBN 3540-55940-X (real-life thread applications).
1017

Acknowledgements

1019       Thanks (in no particular order) to Chaim Frenkel, Steve Fink, Gurusamy
1020       Sarathy, Ilya Zakharevich, Benjamin Sugars, Jürgen Christoffel, Joshua
1021       Pritikin, and Alan Burlison, for their help in reality-checking and
1022       polishing this article.  Big thanks to Tom Christiansen for his rewrite
1023       of the prime number generator.
1024

AUTHOR

1026       Dan Sugalski <sugalskd@ous.edu>
1027

Copyrights

1029       This article originally appeared in The Perl Journal #10, and is copy‐
1030       right 1998 The Perl Journal. It appears courtesy of Jon Orwant and The
1031       Perl Journal.  This document may be distributed under the same terms as
1032       Perl itself.
1033
1034
1035
1036perl v5.8.8                       2006-01-07                    PERLOTHRTUT(1)
Impressum