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