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