Leaked source code of windows server 2003
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1067 lines
41 KiB

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