File: perlthrtut.html

package info (click to toggle)
perl-doc-html 5.26.0-4
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 39,400 kB
  • sloc: xml: 36; makefile: 7
file content (1206 lines) | stat: -rw-r--r-- 114,626 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <title>perlthrtut - perldoc.perl.org</title>
  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
  <meta http-equiv="Content-Language" content="en-gb">
  <link rel="search" type="application/opensearchdescription+xml" title="Search perldoc.perl.org" href="/static/search.xml"/>
  <link href="static/css-20100830.css" rel="stylesheet" rev="stylesheet" type="text/css" media="screen">
  <link href="static/exploreperl.css" rel="stylesheet" rev="stylesheet" type="text/css">
</head>

<body onLoad="perldoc.startup();" onPageShow="if (event.persisted) perldoc.startup();">
    <div id="page">
      
      <div id="header">
	<div id="homepage_link">
	  <a href="index.html"></a>
	</div>
	<div id="strapline">
	  Perl Programming Documentation
	</div>
	<div id="download_link" class="download">
	  <a href="http://www.perl.org/get.html">Download Perl</a>
	</div>
	<div id="explore_link" class="download">
	  <a id="explore_anchor" href="#">Explore</a>
	</div>
      </div>
      
      <div id="body">
        <div id="left_column">
          <div class="side_group">
            
	    <div class="side_panel doc_panel">
              <p>Manual</p>
              <ul>
                <li><a href="index-overview.html">Overview</a>
                <li><a href="index-tutorials.html">Tutorials</a>
                <li><a href="index-faq.html">FAQs</a>
                <li><a href="index-history.html">History / Changes</a>
                <li><a href="index-licence.html">License</a>
              </ul>
            </div>
            <div class="side_panel doc_panel">
              <p>Reference</p>
              <ul>
                <li><a href="index-language.html">Language</a>
                <li><a href="index-functions.html">Functions</a>
                <li><a href="perlop.html">Operators</a>
                <li><a href="perlvar.html">Special Variables</a>
                <li><a href="index-pragmas.html">Pragmas</a>
                <li><a href="index-utilities.html">Utilities</a>
                <li><a href="index-internals.html">Internals</a>
                <li><a href="index-platforms.html">Platform Specific</a>
              </ul>
            </div>
            <div class="side_panel doc_panel">
              <p>Modules</p>
              <ul>
		<li>
		
                
                  
		    
		  
		
                  
		    
		  
		
                  
		    
		  
		
                  
		    
		  
		
                  
		    
		  
		
                  
		    
		  
		
                  
		    
		  
		
                  
		    
		  
		
                  
		    
		  
		
                  
		
                  
		
                  
		    
		  
		
                  
		    
		  
		
                  
		    
		  
		
                  
		    
		  
		
                  
		    
		  
		
                  
		
                  
		
                  
		    
		  
		
                  
		    
		  
		
                  
		    
		  
		
                  
		
                  
		
                  
		    
		  
		
                  
		
                  
		
		
                    <a href="index-modules-A.html">A</a>
                    
                      
                        &bull;
                      
                    
                
                    <a href="index-modules-B.html">B</a>
                    
                      
                        &bull;
                      
                    
                
                    <a href="index-modules-C.html">C</a>
                    
                      
                        &bull;
                      
                    
                
                    <a href="index-modules-D.html">D</a>
                    
                      
                        &bull;
                      
                    
                
                    <a href="index-modules-E.html">E</a>
                    
                      
                        <li>
                      
                    
                
                    <a href="index-modules-F.html">F</a>
                    
                      
                        &bull;
                      
                    
                
                    <a href="index-modules-G.html">G</a>
                    
                      
                        &bull;
                      
                    
                
                    <a href="index-modules-H.html">H</a>
                    
                      
                        &bull;
                      
                    
                
                    <a href="index-modules-I.html">I</a>
                    
                      
                        &bull;
                      
                    
                
                    <a href="index-modules-L.html">L</a>
                    
                      
                        <li>
                      
                    
                
                    <a href="index-modules-M.html">M</a>
                    
                      
                        &bull;
                      
                    
                
                    <a href="index-modules-N.html">N</a>
                    
                      
                        &bull;
                      
                    
                
                    <a href="index-modules-O.html">O</a>
                    
                      
                        &bull;
                      
                    
                
                    <a href="index-modules-P.html">P</a>
                    
                      
                        &bull;
                      
                    
                
                    <a href="index-modules-S.html">S</a>
                    
                      
                        <li>
                      
                    
                
                    <a href="index-modules-T.html">T</a>
                    
                      
                        &bull;
                      
                    
                
                    <a href="index-modules-U.html">U</a>
                    
                      
                        &bull;
                      
                    
                
                    <a href="index-modules-X.html">X</a>
                    
                
              </ul>
            </div>
            
	      <div class="side_panel doc_panel">
		<p>Tools</p>
		<ul>
		  <li><a href="preferences.html">Preferences</a>
		</ul>
	      </div>
            
          </div>
        </div>
        <div id="centre_column">
          <div id="content_header">
            <div id="title_bar">
              <div id="page_name">
                <h1>perlthrtut</h1>
              </div>
              <div id="perl_version">
                Perl 5 version 26.0 documentation
              </div>
              <div class="page_links" id="page_links_top">
                <a href="#" onClick="toolbar.goToTop();return false;">Go to top</a>
		
              </div>
	      <div class="page_links" id="page_links_bottom">
		
                  <a href="#" id="page_index_toggle">Show page index</a> &bull;
		
                <a href="#" id="recent_pages_toggle">Show recent pages</a>		
	      </div>
	      <div id="search_form">
		<form action="search.html" method="GET" id="search">
		  <input type="text" name="q" id="search_box" alt="Search">
		</form>
	      </div>
            </div>
            <div id="breadcrumbs">
                
    <a href="index.html">Home</a> &gt;
    
      
        <a href="index-tutorials.html">Tutorials</a> &gt;
      
    
    perlthrtut
  

            </div>
          </div>
          <div id="content_body">
	    <!--[if lt IE 7]>
 <div class="noscript">
   <p>
     <strong>It looks like you're using Internet Explorer 6. This is a very old
     browser which does not offer full support for modern websites.</strong>
   </p>
   <p>
     Unfortunately this means that this website will not work on
     your computer.
   </p>
   <p>
     Don't miss out though! To view the site (and get a better experience from
     many other websites), simply upgrade to
     <a href="http://www.microsoft.com/windows/Internet-explorer/default.aspx">Internet
Explorer 8</a>
     or download an alternative browser such as
     <a href="http://www.mozilla.com/en-US/firefox/firefox.html">Firefox</a>,
     <a href="http://www.apple.com/safari/download/">Safari</a>, or
     <a href="http://www.google.co.uk/chrome">Google Chrome</a>.
   </p>
   <p>
     All of these browsers are free. If you're using a PC at work, you may
     need to contact your IT administrator.
   </p>
 </div>
<![endif]-->
	    <noscript>
	      <div class="noscript">
	      <p>
                <strong>Please note: Many features of this site require JavaScript. You appear to have JavaScript disabled,
	        or are running a non-JavaScript capable web browser.</strong>
	      </p>
	      <p>
		To get the best experience, please enable JavaScript or download a modern web browser such as <a href="http://www.microsoft.com/windows/Internet-explorer/default.aspx">Internet Explorer 8</a>, <a href="http://www.mozilla.com/en-US/firefox/firefox.html">Firefox</a>, <a href="http://www.apple.com/safari/download/">Safari</a>, or <a href="http://www.google.co.uk/chrome">Google Chrome</a>.
              </p>
	      </div>
	    </noscript>

	    <div id="recent_pages" class="hud_container">
	      <div id="recent_pages_header" class="hud_header">
		<div id="recent_pages_close" class="hud_close"><a href="#" onClick="recentPages.hide();return false;"></a></div>
		<div id="recent_pages_title" class="hud_title"><span class="hud_span_top">Recently read</span></div>
		<div id="recent_pages_topright" class="hud_topright"></div>
	      </div>
	      <div id="recent_pages_content" class="hud_content">
	      </div>
	      <div id="recent_pages_footer" class="hud_footer">
		<div id="recent_pages_bottomleft" class="hud_bottomleft"></div>
		<div id="recent_pages_bottom" class="hud_bottom"><span class="hud_span_bottom"></span></div>
		<div id="recent_pages_resize" class="hud_resize"></div>
	      </div>
	    </div>
  
	    <div id="from_search"></div>
            <h1>perlthrtut</h1>


  <!--    -->
<ul><li><a href="#NAME">NAME</a><li><a href="#DESCRIPTION">DESCRIPTION</a><li><a href="#What-Is-A-Thread-Anyway%3f">What Is A Thread Anyway?</a><li><a href="#Threaded-Program-Models">Threaded Program Models</a><ul><li><a href="#Boss%2fWorker">Boss/Worker</a><li><a href="#Work-Crew">Work Crew</a><li><a href="#Pipeline">Pipeline</a></ul><li><a href="#What-kind-of-threads-are-Perl-threads%3f">What kind of threads are Perl threads?</a><li><a href="#Thread-Safe-Modules">Thread-Safe Modules</a><li><a href="#Thread-Basics">Thread Basics</a><ul><li><a href="#Basic-Thread-Support">Basic Thread Support</a><li><a href="#A-Note-about-the-Examples">A Note about the Examples</a><li><a href="#Creating-Threads">Creating Threads</a><li><a href="#Waiting-For-A-Thread-To-Exit">Waiting For A Thread To Exit</a><li><a href="#Ignoring-A-Thread">Ignoring A Thread</a><li><a href="#Process-and-Thread-Termination">Process and Thread Termination</a></ul><li><a href="#Threads-And-Data">Threads And Data</a><ul><li><a href="#Shared-And-Unshared-Data">Shared And Unshared Data</a><li><a href="#Thread-Pitfalls%3a-Races">Thread Pitfalls: Races</a></ul><li><a href="#Synchronization-and-control">Synchronization and control</a><ul><li><a href="#Controlling-access%3a-lock()">Controlling access: lock()</a><li><a href="#A-Thread-Pitfall%3a-Deadlocks">A Thread Pitfall: Deadlocks</a><li><a href="#Queues%3a-Passing-Data-Around">Queues: Passing Data Around</a><li><a href="#Semaphores%3a-Synchronizing-Data-Access">Semaphores: Synchronizing Data Access</a><li><a href="#Basic-semaphores">Basic semaphores</a><li><a href="#Advanced-Semaphores">Advanced Semaphores</a><li><a href="#Waiting-for-a-Condition">Waiting for a Condition</a><li><a href="#Giving-up-control">Giving up control</a></ul><li><a href="#General-Thread-Utility-Routines">General Thread Utility Routines</a><ul><li><a href="#What-Thread-Am-I-In%3f">What Thread Am I In?</a><li><a href="#Thread-IDs">Thread IDs</a><li><a href="#Are-These-Threads-The-Same%3f">Are These Threads The Same?</a><li><a href="#What-Threads-Are-Running%3f">What Threads Are Running?</a></ul><li><a href="#A-Complete-Example">A Complete Example</a><li><a href="#Different-implementations-of-threads">Different implementations of threads</a><li><a href="#Performance-considerations">Performance considerations</a><li><a href="#Process-scope-Changes">Process-scope Changes</a><li><a href="#Thread-Safety-of-System-Libraries">Thread-Safety of System Libraries</a><li><a href="#Conclusion">Conclusion</a><li><a href="#SEE-ALSO">SEE ALSO</a><li><a href="#Bibliography">Bibliography</a><ul><li><a href="#Introductory-Texts">Introductory Texts</a><li><a href="#OS-Related-References">OS-Related References</a><li><a href="#Other-References">Other References</a></ul><li><a href="#Acknowledgements">Acknowledgements</a><li><a href="#AUTHOR">AUTHOR</a><li><a href="#Copyrights">Copyrights</a></ul><a name="NAME"></a><h1>NAME</h1>
<p>perlthrtut - Tutorial on threads in Perl</p>
<a name="DESCRIPTION"></a><h1>DESCRIPTION</h1>
<p>This tutorial describes the use of Perl interpreter threads (sometimes
referred to as <i>ithreads</i>).  In this
model, each thread runs in its own Perl interpreter, and any data sharing
between threads must be explicit.  The user-level interface for <i>ithreads</i>
uses the <a href="threads.html">threads</a> class.</p>
<p><b>NOTE</b>: There was another older Perl threading flavor called the 5.005 model
that used the <a href="threads.html">threads</a> class.  This old model was known to have problems, is
deprecated, and was removed for release 5.10.  You are
strongly encouraged to migrate any existing 5.005 threads code to the new
model as soon as possible.</p>
<p>You can see which (or neither) threading flavour you have by
running <code class="inline"><span class="w">perl</span> -<span class="w">V</span></code>
 and looking at the <code class="inline"><span class="w">Platform</span></code>
 section.
If you have <code class="inline"><span class="w">useithreads</span>=<span class="w">define</span></code>
 you have ithreads, if you
have <code class="inline"><span class="w">use5005threads</span>=<span class="w">define</span></code>
 you have 5.005 threads.
If you have neither, you don't have any thread support built in.
If you have both, you are in trouble.</p>
<p>The <a href="threads.html">threads</a> and <a href="threads/shared.html">threads::shared</a> modules are included in the core Perl
distribution.  Additionally, they are maintained as a separate modules on
CPAN, so you can check there for any updates.</p>
<a name="What-Is-A-Thread-Anyway%3f"></a><h1>What Is A Thread Anyway?</h1>
<p>A thread is a flow of control through a program with a single
execution point.</p>
<p>Sounds an awful lot like a process, doesn't it? Well, it should.
Threads are one of the pieces of a process.  Every process has at least
one thread and, up until now, every process running Perl had only one
thread.  With 5.8, though, you can create extra threads.  We're going
to show you how, when, and why.</p>
<a name="Threaded-Program-Models"></a><h1>Threaded Program Models</h1>
<p>There are three basic ways that you can structure a threaded
program.  Which model you choose depends on what you need your program
to do.  For many non-trivial threaded programs, you'll need to choose
different models for different pieces of your program.</p>
<a name="Boss%2fWorker"></a><h2>Boss/Worker</h2>
<p>The boss/worker model usually has one <i>boss</i> thread and one or more
<i>worker</i> threads.  The boss thread gathers or generates tasks that need
to be done, then parcels those tasks out to the appropriate worker
thread.</p>
<p>This model is common in GUI and server programs, where a main thread
waits for some event and then passes that event to the appropriate
worker threads for processing.  Once the event has been passed on, the
boss thread goes back to waiting for another event.</p>
<p>The boss thread does relatively little work.  While tasks aren't
necessarily performed faster than with any other method, it tends to
have the best user-response times.</p>
<a name="Work-Crew"></a><h2>Work Crew</h2>
<p>In the work crew model, several threads are created that do
essentially the same thing to different pieces of data.  It closely
mirrors classical parallel processing and vector processors, where a
large array of processors do the exact same thing to many pieces of
data.</p>
<p>This model is particularly useful if the system running the program
will distribute multiple threads across different processors.  It can
also be useful in ray tracing or rendering engines, where the
individual threads can pass on interim results to give the user visual
feedback.</p>
<a name="Pipeline"></a><h2>Pipeline</h2>
<p>The pipeline model divides up a task into a series of steps, and
passes the results of one step on to the thread processing the
next.  Each thread does one thing to each piece of data and passes the
results to the next thread in line.</p>
<p>This model makes the most sense if you have multiple processors so two
or more threads will be executing in parallel, though it can often
make sense in other contexts as well.  It tends to keep the individual
tasks small and simple, as well as allowing some parts of the pipeline
to block (on I/O or system calls, for example) while other parts keep
going.  If you're running different parts of the pipeline on different
processors you may also take advantage of the caches on each
processor.</p>
<p>This model is also handy for a form of recursive programming where,
rather than having a subroutine call itself, it instead creates
another thread.  Prime and Fibonacci generators both map well to this
form of the pipeline model. (A version of a prime number generator is
presented later on.)</p>
<a name="What-kind-of-threads-are-Perl-threads%3f"></a><h1>What kind of threads are Perl threads?</h1>
<p>If you have experience with other thread implementations, you might
find that things aren't quite what you expect.  It's very important to
remember when dealing with Perl threads that <i>Perl Threads Are Not X
Threads</i> for all values of X.  They aren't POSIX threads, or
DecThreads, or Java's Green threads, or Win32 threads.  There are
similarities, and the broad concepts are the same, but if you start
looking for implementation details you're going to be either
disappointed or confused.  Possibly both.</p>
<p>This is not to say that Perl threads are completely different from
everything that's ever come before. They're not.  Perl's threading
model owes a lot to other thread models, especially POSIX.  Just as
Perl is not C, though, Perl threads are not POSIX threads.  So if you
find yourself looking for mutexes, or thread priorities, it's time to
step back a bit and think about what you want to do and how Perl can
do it.</p>
<p>However, it is important to remember that Perl threads cannot magically
do things unless your operating system's threads allow it. So if your
system blocks the entire process on <code class="inline"><a class="l_k" href="functions/sleep.html">sleep()</a></code>, Perl usually will, as well.</p>
<p><b>Perl Threads Are Different.</b></p>
<a name="Thread-Safe-Modules"></a><h1>Thread-Safe Modules</h1>
<p>The addition of threads has changed Perl's internals
substantially. There are implications for people who write
modules with XS code or external libraries. However, since Perl data is
not shared among threads by default, Perl modules stand a high chance of
being thread-safe or can be made thread-safe easily.  Modules that are not
tagged as thread-safe should be tested or code reviewed before being used
in production code.</p>
<p>Not all modules that you might use are thread-safe, and you should
always assume a module is unsafe unless the documentation says
otherwise.  This includes modules that are distributed as part of the
core.  Threads are a relatively new feature, and even some of the standard
modules aren't thread-safe.</p>
<p>Even if a module is thread-safe, it doesn't mean that the module is optimized
to work well with threads. A module could possibly be rewritten to utilize
the new features in threaded Perl to increase performance in a threaded
environment.</p>
<p>If you're using a module that's not thread-safe for some reason, you
can protect yourself by using it from one, and only one thread at all.
If you need multiple threads to access such a module, you can use semaphores and
lots of programming discipline to control access to it.  Semaphores
are covered in <a href="#Basic-semaphores">Basic semaphores</a>.</p>
<p>See also <a href="#Thread-Safety-of-System-Libraries">Thread-Safety of System Libraries</a>.</p>
<a name="Thread-Basics"></a><h1>Thread Basics</h1>
<p>The <a href="threads.html">threads</a> module provides the basic functions you need to write
threaded programs.  In the following sections, we'll cover the basics,
showing you what you need to do to create a threaded program.   After
that, we'll go over some of the features of the <a href="threads.html">threads</a> module that
make threaded programming easier.</p>
<a name="Basic-Thread-Support"></a><h2>Basic Thread Support</h2>
<p>Thread support is a Perl compile-time option. It's something that's
turned on or off when Perl is built at your site, rather than when
your programs are compiled. If your Perl wasn't compiled with thread
support enabled, then any attempt to use threads will fail.</p>
<p>Your programs can use the Config module to check whether threads are
enabled. If your program can't run without them, you can say something
like:</p>
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/use.html">use</a> <span class="w">Config</span><span class="sc">;</span></li><li>    <span class="i">$Config</span>{<span class="w">useithreads</span>} <a class="l_k" href="functions/or.html">or</a></li><li>        <a class="l_k" href="functions/die.html">die</a><span class="s">(</span><span class="q">&#39;Recompile Perl with threads to run this program.&#39;</span><span class="s">)</span><span class="sc">;</span></li></ol></pre><p>A possibly-threaded program using a possibly-threaded module might
have code like this:</p>
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/use.html">use</a> <span class="w">Config</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/use.html">use</a> <span class="w">MyMod</span><span class="sc">;</span></li><li></li><li>    BEGIN <span class="s">{</span></li><li>        if <span class="s">(</span><span class="i">$Config</span>{<span class="w">useithreads</span>}<span class="s">)</span> <span class="s">{</span></li><li>            <span class="c"># We have threads</span></li><li>            <a class="l_k" href="functions/require.html">require</a> <span class="w">MyMod_threaded</span><span class="sc">;</span></li><li>            <span class="w">import</span> <span class="w">MyMod_threaded</span><span class="sc">;</span></li><li>        <span class="s">}</span> else <span class="s">{</span></li><li>            <a class="l_k" href="functions/require.html">require</a> <span class="w">MyMod_unthreaded</span><span class="sc">;</span></li><li>            <span class="w">import</span> <span class="w">MyMod_unthreaded</span><span class="sc">;</span></li><li>        <span class="s">}</span></li><li>    <span class="s">}</span></li></ol></pre><p>Since code that runs both with and without threads is usually pretty
messy, it's best to isolate the thread-specific code in its own
module.  In our example above, that's what <code class="inline"><span class="w">MyMod_threaded</span></code>
 is, and it's
only imported if we're running on a threaded Perl.</p>
<a name="A-Note-about-the-Examples"></a><h2>A Note about the Examples</h2>
<p>In a real situation, care should be taken that all threads are finished
executing before the program exits.  That care has <b>not</b> been taken in these
examples in the interest of simplicity.  Running these examples <i>as is</i> will
produce error messages, usually caused by the fact that there are still
threads running when the program exits.  You should not be alarmed by this.</p>
<a name="Creating-Threads"></a><h2>Creating Threads</h2>
<p>The <a href="threads.html">threads</a> module provides the tools you need to create new
threads.  Like any other module, you need to tell Perl that you want to use
it; <code class="inline"><a class="l_k" href="functions/use.html">use</a> <span class="w">threads</span><span class="sc">;</span></code>
 imports all the pieces you need to create basic
threads.</p>
<p>The simplest, most straightforward way to create a thread is with <code class="inline"><span class="i">create</span><span class="s">(</span><span class="s">)</span></code>
:</p>
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/use.html">use</a> <span class="w">threads</span><span class="sc">;</span></li><li></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$thr</span> = <span class="w">threads</span><span class="w">-&gt;create</span><span class="s">(</span>\<span class="i">&amp;sub1</span><span class="s">)</span><span class="sc">;</span></li><li></li><li><a name="sub1"></a>    sub <span class="m">sub1</span> <span class="s">{</span></li><li>        <a class="l_k" href="functions/print.html">print</a><span class="s">(</span><span class="q">&quot;In the thread\n&quot;</span><span class="s">)</span><span class="sc">;</span></li><li>    <span class="s">}</span></li></ol></pre><p>The <code class="inline"><span class="i">create</span><span class="s">(</span><span class="s">)</span></code>
 method takes a reference to a subroutine and creates a new
thread that starts executing in the referenced subroutine.  Control
then passes both to the subroutine and the caller.</p>
<p>If you need to, your program can pass parameters to the subroutine as
part of the thread startup.  Just include the list of parameters as
part of the <code class="inline"><span class="w">threads</span><span class="w">-&gt;create</span><span class="s">(</span><span class="s">)</span></code>
 call, like this:</p>
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/use.html">use</a> <span class="w">threads</span><span class="sc">;</span></li><li></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$Param3</span> = <span class="q">&#39;foo&#39;</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$thr1</span> = <span class="w">threads</span><span class="w">-&gt;create</span><span class="s">(</span>\<span class="i">&amp;sub1</span><span class="cm">,</span> <span class="q">&#39;Param 1&#39;</span><span class="cm">,</span> <span class="q">&#39;Param 2&#39;</span><span class="cm">,</span> <span class="i">$Param3</span><span class="s">)</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">@ParamList</span> = <span class="s">(</span><span class="n">42</span><span class="cm">,</span> <span class="q">&#39;Hello&#39;</span><span class="cm">,</span> <span class="n">3.14</span><span class="s">)</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$thr2</span> = <span class="w">threads</span><span class="w">-&gt;create</span><span class="s">(</span>\<span class="i">&amp;sub1</span><span class="cm">,</span> <span class="i">@ParamList</span><span class="s">)</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$thr3</span> = <span class="w">threads</span><span class="w">-&gt;create</span><span class="s">(</span>\<span class="i">&amp;sub1</span><span class="cm">,</span> <span class="q">qw(Param1 Param2 Param3)</span><span class="s">)</span><span class="sc">;</span></li><li></li><li><a name="sub1"></a>    sub <span class="m">sub1</span> <span class="s">{</span></li><li>        <a class="l_k" href="functions/my.html">my</a> <span class="i">@InboundParameters</span> = <span class="i">@_</span><span class="sc">;</span></li><li>        <a class="l_k" href="functions/print.html">print</a><span class="s">(</span><span class="q">&quot;In the thread\n&quot;</span><span class="s">)</span><span class="sc">;</span></li><li>        <a class="l_k" href="functions/print.html">print</a><span class="s">(</span><span class="q">&#39;Got parameters &gt;&#39;</span><span class="cm">,</span> <a class="l_k" href="functions/join.html">join</a><span class="s">(</span><span class="q">&#39;&lt;&gt;&#39;</span><span class="cm">,</span><span class="i">@InboundParameters</span><span class="s">)</span><span class="cm">,</span> <span class="q">&quot;&lt;\n&quot;</span><span class="s">)</span><span class="sc">;</span></li><li>    <span class="s">}</span></li></ol></pre><p>The last example illustrates another feature of threads.  You can spawn
off several threads using the same subroutine.  Each thread executes
the same subroutine, but in a separate thread with a separate
environment and potentially separate arguments.</p>
<p><code class="inline"><span class="i">new</span><span class="s">(</span><span class="s">)</span></code>
 is a synonym for <code class="inline"><span class="i">create</span><span class="s">(</span><span class="s">)</span></code>
.</p>
<a name="Waiting-For-A-Thread-To-Exit"></a><h2>Waiting For A Thread To Exit</h2>
<p>Since threads are also subroutines, they can return values.  To wait
for a thread to exit and extract any values it might return, you can
use the <code class="inline"><a class="l_k" href="functions/join.html">join()</a></code> method:</p>
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/use.html">use</a> <span class="w">threads</span><span class="sc">;</span></li><li></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="s">(</span><span class="i">$thr</span><span class="s">)</span> = <span class="w">threads</span><span class="w">-&gt;create</span><span class="s">(</span>\<span class="i">&amp;sub1</span><span class="s">)</span><span class="sc">;</span></li><li></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">@ReturnData</span> = <span class="i">$thr</span><span class="i">-&gt;join</span><span class="s">(</span><span class="s">)</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/print.html">print</a><span class="s">(</span><span class="q">&#39;Thread returned &#39;</span><span class="cm">,</span> <a class="l_k" href="functions/join.html">join</a><span class="s">(</span><span class="q">&#39;, &#39;</span><span class="cm">,</span> <span class="i">@ReturnData</span><span class="s">)</span><span class="cm">,</span> <span class="q">&quot;\n&quot;</span><span class="s">)</span><span class="sc">;</span></li><li></li><li><a name="sub1"></a>    sub <span class="m">sub1</span> <span class="s">{</span> <a class="l_k" href="functions/return.html">return</a> <span class="s">(</span><span class="q">&#39;Fifty-six&#39;</span><span class="cm">,</span> <span class="q">&#39;foo&#39;</span><span class="cm">,</span> <span class="n">2</span><span class="s">)</span><span class="sc">;</span> <span class="s">}</span></li></ol></pre><p>In the example above, the <code class="inline"><a class="l_k" href="functions/join.html">join()</a></code> method returns as soon as the thread
ends.  In addition to waiting for a thread to finish and gathering up
any values that the thread might have returned, <code class="inline"><a class="l_k" href="functions/join.html">join()</a></code> also performs
any OS cleanup necessary for the thread.  That cleanup might be
important, especially for long-running programs that spawn lots of
threads.  If you don't want the return values and don't want to wait
for the thread to finish, you should call the <code class="inline"><span class="i">detach</span><span class="s">(</span><span class="s">)</span></code>
 method
instead, as described next.</p>
<p>NOTE: In the example above, the thread returns a list, thus necessitating
that the thread creation call be made in list context (i.e., <code class="inline"><a class="l_k" href="functions/my.html">my</a> <span class="s">(</span><span class="i">$thr</span><span class="s">)</span></code>
).
See <a href="threads.html#%24thr-%3ejoin()">$thr-&gt;join() in threads</a> and <a href="threads.html#THREAD-CONTEXT">THREAD CONTEXT in threads</a> for more
details on thread context and return values.</p>
<a name="Ignoring-A-Thread"></a><h2>Ignoring A Thread</h2>
<p><code class="inline"><a class="l_k" href="functions/join.html">join()</a></code> does three things: it waits for a thread to exit, cleans up
after it, and returns any data the thread may have produced.  But what
if you're not interested in the thread's return values, and you don't
really care when the thread finishes? All you want is for the thread
to get cleaned up after when it's done.</p>
<p>In this case, you use the <code class="inline"><span class="i">detach</span><span class="s">(</span><span class="s">)</span></code>
 method.  Once a thread is detached,
it'll run until it's finished; then Perl will clean up after it
automatically.</p>
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/use.html">use</a> <span class="w">threads</span><span class="sc">;</span></li><li></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$thr</span> = <span class="w">threads</span><span class="w">-&gt;create</span><span class="s">(</span>\<span class="i">&amp;sub1</span><span class="s">)</span><span class="sc">;</span>   <span class="c"># Spawn the thread</span></li><li></li><li>    <span class="i">$thr</span><span class="i">-&gt;detach</span><span class="s">(</span><span class="s">)</span><span class="sc">;</span>   <span class="c"># Now we officially don&#39;t care any more</span></li><li></li><li>    <a class="l_k" href="functions/sleep.html">sleep</a><span class="s">(</span><span class="n">15</span><span class="s">)</span><span class="sc">;</span>        <span class="c"># Let thread run for awhile</span></li><li></li><li><a name="sub1"></a>    sub <span class="m">sub1</span> <span class="s">{</span></li><li>        <a class="l_k" href="functions/my.html">my</a> <span class="i">$count</span> = <span class="n">0</span><span class="sc">;</span></li><li>        <a class="l_k" href="functions/while.html">while</a> <span class="s">(</span><span class="n">1</span><span class="s">)</span> <span class="s">{</span></li><li>            <span class="i">$count</span>++<span class="sc">;</span></li><li>            <a class="l_k" href="functions/print.html">print</a><span class="s">(</span><span class="q">&quot;\$count is $count\n&quot;</span><span class="s">)</span><span class="sc">;</span></li><li>            <a class="l_k" href="functions/sleep.html">sleep</a><span class="s">(</span><span class="n">1</span><span class="s">)</span><span class="sc">;</span></li><li>        <span class="s">}</span></li><li>    <span class="s">}</span></li></ol></pre><p>Once a thread is detached, it may not be joined, and any return data
that it might have produced (if it was done and waiting for a join) is
lost.</p>
<p><code class="inline"><span class="i">detach</span><span class="s">(</span><span class="s">)</span></code>
 can also be called as a class method to allow a thread to
detach itself:</p>
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/use.html">use</a> <span class="w">threads</span><span class="sc">;</span></li><li></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$thr</span> = <span class="w">threads</span><span class="w">-&gt;create</span><span class="s">(</span>\<span class="i">&amp;sub1</span><span class="s">)</span><span class="sc">;</span></li><li></li><li><a name="sub1"></a>    sub <span class="m">sub1</span> <span class="s">{</span></li><li>        <span class="w">threads</span><span class="w">-&gt;detach</span><span class="s">(</span><span class="s">)</span><span class="sc">;</span></li><li>        <span class="c"># Do more work</span></li><li>    <span class="s">}</span></li></ol></pre><a name="Process-and-Thread-Termination"></a><h2>Process and Thread Termination</h2>
<p>With threads one must be careful to make sure they all have a chance to
run to completion, assuming that is what you want.</p>
<p>An action that terminates a process will terminate <i>all</i> running
threads.  die() and exit() have this property,
and perl does an exit when the main thread exits,
perhaps implicitly by falling off the end of your code,
even if that's not what you want.</p>
<p>As an example of this case, this code prints the message
"Perl exited with active threads: 2 running and unjoined":</p>
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/use.html">use</a> <span class="w">threads</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$thr1</span> = <span class="w">threads</span><span class="w">-&gt;new</span><span class="s">(</span>\<span class="i">&amp;thrsub</span><span class="cm">,</span> <span class="q">&quot;test1&quot;</span><span class="s">)</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$thr2</span> = <span class="w">threads</span><span class="w">-&gt;new</span><span class="s">(</span>\<span class="i">&amp;thrsub</span><span class="cm">,</span> <span class="q">&quot;test2&quot;</span><span class="s">)</span><span class="sc">;</span></li><li><a name="thrsub"></a>    sub <span class="m">thrsub</span> <span class="s">{</span></li><li>       <a class="l_k" href="functions/my.html">my</a> <span class="s">(</span><span class="i">$message</span><span class="s">)</span> = <span class="i">@_</span><span class="sc">;</span></li><li>       <a class="l_k" href="functions/sleep.html">sleep</a> <span class="n">1</span><span class="sc">;</span></li><li>       <a class="l_k" href="functions/print.html">print</a> <span class="q">&quot;thread $message\n&quot;</span><span class="sc">;</span></li><li>    <span class="s">}</span></li></ol></pre><p>But when the following lines are added at the end:</p>
<pre class="verbatim"><ol><li>    <span class="i">$thr1</span><span class="i">-&gt;join</span><span class="s">(</span><span class="s">)</span><span class="sc">;</span></li><li>    <span class="i">$thr2</span><span class="i">-&gt;join</span><span class="s">(</span><span class="s">)</span><span class="sc">;</span></li></ol></pre><p>it prints two lines of output, a perhaps more useful outcome.</p>
<a name="Threads-And-Data"></a><h1>Threads And Data</h1>
<p>Now that we've covered the basics of threads, it's time for our next
topic: Data.  Threading introduces a couple of complications to data
access that non-threaded programs never need to worry about.</p>
<a name="Shared-And-Unshared-Data"></a><h2>Shared And Unshared Data</h2>
<p>The biggest difference between Perl <i>ithreads</i> and the old 5.005 style
threading, or for that matter, to most other threading systems out there,
is that by default, no data is shared. When a new Perl thread is created,
all the data associated with the current thread is copied to the new
thread, and is subsequently private to that new thread!
This is similar in feel to what happens when a Unix process forks,
except that in this case, the data is just copied to a different part of
memory within the same process rather than a real fork taking place.</p>
<p>To make use of threading, however, one usually wants the threads to share
at least some data between themselves. This is done with the
<a href="threads/shared.html">threads::shared</a> module and the <code class="inline"><span class="j">:</span><span class="w">shared</span></code>
 attribute:</p>
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/use.html">use</a> <span class="w">threads</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/use.html">use</a> <span class="w">threads::shared</span><span class="sc">;</span></li><li></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$foo</span> <span class="co">:</span><span class="w">shared</span> = <span class="n">1</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$bar</span> = <span class="n">1</span><span class="sc">;</span></li><li>    <span class="w">threads</span><span class="w">-&gt;create</span><span class="s">(</span><a class="l_k" href="functions/sub.html">sub</a> <span class="s">{</span> <span class="i">$foo</span>++<span class="sc">;</span> <span class="i">$bar</span>++<span class="sc">;</span> <span class="s">}</span><span class="s">)</span><span class="i">-&gt;join</span><span class="s">(</span><span class="s">)</span><span class="sc">;</span></li><li></li><li>    <a class="l_k" href="functions/print.html">print</a><span class="s">(</span><span class="q">&quot;$foo\n&quot;</span><span class="s">)</span><span class="sc">;</span>  <span class="c"># Prints 2 since $foo is shared</span></li><li>    <a class="l_k" href="functions/print.html">print</a><span class="s">(</span><span class="q">&quot;$bar\n&quot;</span><span class="s">)</span><span class="sc">;</span>  <span class="c"># Prints 1 since $bar is not shared</span></li></ol></pre><p>In the case of a shared array, all the array's elements are shared, and for
a shared hash, all the keys and values are shared. This places
restrictions on what may be assigned to shared array and hash elements: only
simple values or references to shared variables are allowed - this is
so that a private variable can't accidentally become shared. A bad
assignment will cause the thread to die. For example:</p>
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/use.html">use</a> <span class="w">threads</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/use.html">use</a> <span class="w">threads::shared</span><span class="sc">;</span></li><li></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$var</span>          = <span class="n">1</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$svar</span> <span class="co">:</span><span class="w">shared</span> = <span class="n">2</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">%hash</span> <span class="co">:</span><span class="w">shared</span><span class="sc">;</span></li><li></li><li>    ... <span class="w">create</span> <span class="w">some</span> <span class="w">threads</span> ...</li><li></li><li>    <span class="i">$hash</span>{<span class="w">a</span>} = <span class="n">1</span><span class="sc">;</span>       <span class="c"># All threads see exists($hash{a})</span></li><li>                        <span class="c"># and $hash{a} == 1</span></li><li>    <span class="i">$hash</span>{<span class="w">a</span>} = <span class="i">$var</span><span class="sc">;</span>    <span class="c"># okay - copy-by-value: same effect as previous</span></li><li>    <span class="i">$hash</span>{<span class="w">a</span>} = <span class="i">$svar</span><span class="sc">;</span>   <span class="c"># okay - copy-by-value: same effect as previous</span></li><li>    <span class="i">$hash</span>{<span class="w">a</span>} = \<span class="i">$svar</span><span class="sc">;</span>  <span class="c"># okay - a reference to a shared variable</span></li><li>    <span class="i">$hash</span>{<span class="w">a</span>} = \<span class="i">$var</span><span class="sc">;</span>   <span class="c"># This will die</span></li><li>    <a class="l_k" href="functions/delete.html">delete</a><span class="s">(</span><span class="i">$hash</span>{<span class="w">a</span>}<span class="s">)</span><span class="sc">;</span>   <span class="c"># okay - all threads will see !exists($hash{a})</span></li></ol></pre><p>Note that a shared variable guarantees that if two or more threads try to
modify it at the same time, the internal state of the variable will not
become corrupted. However, there are no guarantees beyond this, as
explained in the next section.</p>
<a name="Thread-Pitfalls%3a-Races"></a><h2>Thread Pitfalls: Races</h2>
<p>While threads bring a new set of useful tools, they also bring a
number of pitfalls.  One pitfall is the race condition:</p>
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/use.html">use</a> <span class="w">threads</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/use.html">use</a> <span class="w">threads::shared</span><span class="sc">;</span></li><li></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$x</span> <span class="co">:</span><span class="w">shared</span> = <span class="n">1</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$thr1</span> = <span class="w">threads</span><span class="w">-&gt;create</span><span class="s">(</span>\<span class="i">&amp;sub1</span><span class="s">)</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$thr2</span> = <span class="w">threads</span><span class="w">-&gt;create</span><span class="s">(</span>\<span class="i">&amp;sub2</span><span class="s">)</span><span class="sc">;</span></li><li></li><li>    <span class="i">$thr1</span><span class="i">-&gt;join</span><span class="s">(</span><span class="s">)</span><span class="sc">;</span></li><li>    <span class="i">$thr2</span><span class="i">-&gt;join</span><span class="s">(</span><span class="s">)</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/print.html">print</a><span class="s">(</span><span class="q">&quot;$x\n&quot;</span><span class="s">)</span><span class="sc">;</span></li><li></li><li><a name="sub1"></a>    sub <span class="m">sub1</span> <span class="s">{</span> <a class="l_k" href="functions/my.html">my</a> <span class="i">$foo</span> = <span class="i">$x</span><span class="sc">;</span> <span class="i">$x</span> = <span class="i">$foo</span> + <span class="n">1</span><span class="sc">;</span> <span class="s">}</span></li><li><a name="sub2"></a>    sub <span class="m">sub2</span> <span class="s">{</span> <a class="l_k" href="functions/my.html">my</a> <span class="i">$bar</span> = <span class="i">$x</span><span class="sc">;</span> <span class="i">$x</span> = <span class="i">$bar</span> + <span class="n">1</span><span class="sc">;</span> <span class="s">}</span></li></ol></pre><p>What do you think <code class="inline"><span class="i">$x</span></code>
 will be? The answer, unfortunately, is <i>it
depends</i>. Both <code class="inline"><span class="i">sub1</span><span class="s">(</span><span class="s">)</span></code>
 and <code class="inline"><span class="i">sub2</span><span class="s">(</span><span class="s">)</span></code>
 access the global variable <code class="inline"><span class="i">$x</span></code>
, once
to read and once to write.  Depending on factors ranging from your
thread implementation's scheduling algorithm to the phase of the moon,
<code class="inline"><span class="i">$x</span></code>
 can be 2 or 3.</p>
<p>Race conditions are caused by unsynchronized access to shared
data.  Without explicit synchronization, there's no way to be sure that
nothing has happened to the shared data between the time you access it
and the time you update it.  Even this simple code fragment has the
possibility of error:</p>
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/use.html">use</a> <span class="w">threads</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$x</span> <span class="co">:</span><span class="w">shared</span> = <span class="n">2</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$y</span> <span class="co">:</span><span class="w">shared</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$z</span> <span class="co">:</span><span class="w">shared</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$thr1</span> = <span class="w">threads</span><span class="w">-&gt;create</span><span class="s">(</span><a class="l_k" href="functions/sub.html">sub</a> <span class="s">{</span> <span class="i">$y</span> = <span class="i">$x</span><span class="sc">;</span> <span class="i">$x</span> = <span class="i">$y</span> + <span class="n">1</span><span class="sc">;</span> <span class="s">}</span><span class="s">)</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$thr2</span> = <span class="w">threads</span><span class="w">-&gt;create</span><span class="s">(</span><a class="l_k" href="functions/sub.html">sub</a> <span class="s">{</span> <span class="i">$z</span> = <span class="i">$x</span><span class="sc">;</span> <span class="i">$x</span> = <span class="i">$z</span> + <span class="n">1</span><span class="sc">;</span> <span class="s">}</span><span class="s">)</span><span class="sc">;</span></li><li>    <span class="i">$thr1</span><span class="i">-&gt;join</span><span class="s">(</span><span class="s">)</span><span class="sc">;</span></li><li>    <span class="i">$thr2</span><span class="i">-&gt;join</span><span class="s">(</span><span class="s">)</span><span class="sc">;</span></li></ol></pre><p>Two threads both access <code class="inline"><span class="i">$x</span></code>
.  Each thread can potentially be interrupted
at any point, or be executed in any order.  At the end, <code class="inline"><span class="i">$x</span></code>
 could be 3
or 4, and both <code class="inline"><span class="i">$y</span></code>
 and <code class="inline"><span class="i">$z</span></code>
 could be 2 or 3.</p>
<p>Even <code class="inline"><span class="i">$x</span> += <span class="n">5</span></code>
 or <code class="inline"><span class="i">$x</span>++</code>
 are not guaranteed to be atomic.</p>
<p>Whenever your program accesses data or resources that can be accessed
by other threads, you must take steps to coordinate access or risk
data inconsistency and race conditions. Note that Perl will protect its
internals from your race conditions, but it won't protect you from you.</p>
<a name="Synchronization-and-control"></a><h1>Synchronization and control</h1>
<p>Perl provides a number of mechanisms to coordinate the interactions
between themselves and their data, to avoid race conditions and the like.
Some of these are designed to resemble the common techniques used in thread
libraries such as <code class="inline"><span class="w">pthreads</span></code>
; others are Perl-specific. Often, the
standard techniques are clumsy and difficult to get right (such as
condition waits). Where possible, it is usually easier to use Perlish
techniques such as queues, which remove some of the hard work involved.</p>
<a name="Controlling-access%3a-lock()"></a><h2>Controlling access: lock()</h2>
<p>The <code class="inline"><a class="l_k" href="functions/lock.html">lock()</a></code> function takes a shared variable and puts a lock on it.
No other thread may lock the variable until the variable is unlocked
by the thread holding the lock. Unlocking happens automatically
when the locking thread exits the block that contains the call to the
<code class="inline"><a class="l_k" href="functions/lock.html">lock()</a></code> function.  Using <code class="inline"><a class="l_k" href="functions/lock.html">lock()</a></code> is straightforward: This example has
several threads doing some calculations in parallel, and occasionally
updating a running total:</p>
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/use.html">use</a> <span class="w">threads</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/use.html">use</a> <span class="w">threads::shared</span><span class="sc">;</span></li><li></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$total</span> <span class="co">:</span><span class="w">shared</span> = <span class="n">0</span><span class="sc">;</span></li><li></li><li><a name="calc"></a>    sub <span class="m">calc</span> <span class="s">{</span></li><li>        while <span class="s">(</span><span class="n">1</span><span class="s">)</span> <span class="s">{</span></li><li>            <a class="l_k" href="functions/my.html">my</a> <span class="i">$result</span><span class="sc">;</span></li><li>            <span class="c"># (... do some calculations and set $result ...)</span></li><li>            <span class="s">{</span></li><li>                <a class="l_k" href="functions/lock.html">lock</a><span class="s">(</span><span class="i">$total</span><span class="s">)</span><span class="sc">;</span>  <span class="c"># Block until we obtain the lock</span></li><li>                <span class="i">$total</span> += <span class="i">$result</span><span class="sc">;</span></li><li>            <span class="s">}</span> <span class="c"># Lock implicitly released at end of scope</span></li><li>            <a class="l_k" href="functions/last.html">last</a> if <span class="i">$result</span> == <span class="n">0</span><span class="sc">;</span></li><li>        <span class="s">}</span></li><li>    <span class="s">}</span></li><li></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$thr1</span> = <span class="w">threads</span><span class="w">-&gt;create</span><span class="s">(</span>\<span class="i">&amp;calc</span><span class="s">)</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$thr2</span> = <span class="w">threads</span><span class="w">-&gt;create</span><span class="s">(</span>\<span class="i">&amp;calc</span><span class="s">)</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$thr3</span> = <span class="w">threads</span><span class="w">-&gt;create</span><span class="s">(</span>\<span class="i">&amp;calc</span><span class="s">)</span><span class="sc">;</span></li><li>    <span class="i">$thr1</span><span class="i">-&gt;join</span><span class="s">(</span><span class="s">)</span><span class="sc">;</span></li><li>    <span class="i">$thr2</span><span class="i">-&gt;join</span><span class="s">(</span><span class="s">)</span><span class="sc">;</span></li><li>    <span class="i">$thr3</span><span class="i">-&gt;join</span><span class="s">(</span><span class="s">)</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/print.html">print</a><span class="s">(</span><span class="q">&quot;total=$total\n&quot;</span><span class="s">)</span><span class="sc">;</span></li></ol></pre><p><code class="inline"><a class="l_k" href="functions/lock.html">lock()</a></code> blocks the thread until the variable being locked is
available.  When <code class="inline"><a class="l_k" href="functions/lock.html">lock()</a></code> returns, your thread can be sure that no other
thread can lock that variable until the block containing the
lock exits.</p>
<p>It's important to note that locks don't prevent access to the variable
in question, only lock attempts.  This is in keeping with Perl's
longstanding tradition of courteous programming, and the advisory file
locking that <code class="inline"><a class="l_k" href="functions/flock.html">flock()</a></code> gives you.</p>
<p>You may lock arrays and hashes as well as scalars.  Locking an array,
though, will not block subsequent locks on array elements, just lock
attempts on the array itself.</p>
<p>Locks are recursive, which means it's okay for a thread to
lock a variable more than once.  The lock will last until the outermost
<code class="inline"><a class="l_k" href="functions/lock.html">lock()</a></code> on the variable goes out of scope. For example:</p>
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$x</span> <span class="co">:</span><span class="w">shared</span><span class="sc">;</span></li><li>    <span class="i">doit</span><span class="s">(</span><span class="s">)</span><span class="sc">;</span></li><li></li><li><a name="doit"></a>    sub <span class="m">doit</span> <span class="s">{</span></li><li>        <span class="s">{</span></li><li>            <span class="s">{</span></li><li>                <a class="l_k" href="functions/lock.html">lock</a><span class="s">(</span><span class="i">$x</span><span class="s">)</span><span class="sc">;</span> <span class="c"># Wait for lock</span></li><li>                <a class="l_k" href="functions/lock.html">lock</a><span class="s">(</span><span class="i">$x</span><span class="s">)</span><span class="sc">;</span> <span class="c"># NOOP - we already have the lock</span></li><li>                <span class="s">{</span></li><li>                    <a class="l_k" href="functions/lock.html">lock</a><span class="s">(</span><span class="i">$x</span><span class="s">)</span><span class="sc">;</span> <span class="c"># NOOP</span></li><li>                    <span class="s">{</span></li><li>                        <a class="l_k" href="functions/lock.html">lock</a><span class="s">(</span><span class="i">$x</span><span class="s">)</span><span class="sc">;</span> <span class="c"># NOOP</span></li><li>                        <span class="i">lockit_some_more</span><span class="s">(</span><span class="s">)</span><span class="sc">;</span></li><li>                    <span class="s">}</span></li><li>                <span class="s">}</span></li><li>            <span class="s">}</span> <span class="c"># *** Implicit unlock here ***</span></li><li>        <span class="s">}</span></li><li>    <span class="s">}</span></li><li></li><li><a name="lockit_some_more"></a>    sub <span class="m">lockit_some_more</span> <span class="s">{</span></li><li>        <a class="l_k" href="functions/lock.html">lock</a><span class="s">(</span><span class="i">$x</span><span class="s">)</span><span class="sc">;</span> <span class="c"># NOOP</span></li><li>    <span class="s">}</span> <span class="c"># Nothing happens here</span></li></ol></pre><p>Note that there is no <code class="inline"><span class="i">unlock</span><span class="s">(</span><span class="s">)</span></code>
 function - the only way to unlock a
variable is to allow it to go out of scope.</p>
<p>A lock can either be used to guard the data contained within the variable
being locked, or it can be used to guard something else, like a section
of code. In this latter case, the variable in question does not hold any
useful data, and exists only for the purpose of being locked. In this
respect, the variable behaves like the mutexes and basic semaphores of
traditional thread libraries.</p>
<a name="A-Thread-Pitfall%3a-Deadlocks"></a><h2>A Thread Pitfall: Deadlocks</h2>
<p>Locks are a handy tool to synchronize access to data, and using them
properly is the key to safe shared data.  Unfortunately, locks aren't
without their dangers, especially when multiple locks are involved.
Consider the following code:</p>
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/use.html">use</a> <span class="w">threads</span><span class="sc">;</span></li><li></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$x</span> <span class="co">:</span><span class="w">shared</span> = <span class="n">4</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$y</span> <span class="co">:</span><span class="w">shared</span> = <span class="q">&#39;foo&#39;</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$thr1</span> = <span class="w">threads</span><span class="w">-&gt;create</span><span class="s">(</span><a class="l_k" href="functions/sub.html">sub</a> <span class="s">{</span></li><li>        <a class="l_k" href="functions/lock.html">lock</a><span class="s">(</span><span class="i">$x</span><span class="s">)</span><span class="sc">;</span></li><li>        <a class="l_k" href="functions/sleep.html">sleep</a><span class="s">(</span><span class="n">20</span><span class="s">)</span><span class="sc">;</span></li><li>        <a class="l_k" href="functions/lock.html">lock</a><span class="s">(</span><span class="i">$y</span><span class="s">)</span><span class="sc">;</span></li><li>    <span class="s">}</span><span class="s">)</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$thr2</span> = <span class="w">threads</span><span class="w">-&gt;create</span><span class="s">(</span><a class="l_k" href="functions/sub.html">sub</a> <span class="s">{</span></li><li>        <a class="l_k" href="functions/lock.html">lock</a><span class="s">(</span><span class="i">$y</span><span class="s">)</span><span class="sc">;</span></li><li>        <a class="l_k" href="functions/sleep.html">sleep</a><span class="s">(</span><span class="n">20</span><span class="s">)</span><span class="sc">;</span></li><li>        <a class="l_k" href="functions/lock.html">lock</a><span class="s">(</span><span class="i">$x</span><span class="s">)</span><span class="sc">;</span></li><li>    <span class="s">}</span><span class="s">)</span><span class="sc">;</span></li></ol></pre><p>This program will probably hang until you kill it.  The only way it
won't hang is if one of the two threads acquires both locks
first.  A guaranteed-to-hang version is more complicated, but the
principle is the same.</p>
<p>The first thread will grab a lock on <code class="inline"><span class="i">$x</span></code>
, then, after a pause during which
the second thread has probably had time to do some work, try to grab a
lock on <code class="inline"><span class="i">$y</span></code>
.  Meanwhile, the second thread grabs a lock on <code class="inline"><span class="i">$y</span></code>
, then later
tries to grab a lock on <code class="inline"><span class="i">$x</span></code>
.  The second lock attempt for both threads will
block, each waiting for the other to release its lock.</p>
<p>This condition is called a deadlock, and it occurs whenever two or
more threads are trying to get locks on resources that the others
own.  Each thread will block, waiting for the other to release a lock
on a resource.  That never happens, though, since the thread with the
resource is itself waiting for a lock to be released.</p>
<p>There are a number of ways to handle this sort of problem.  The best
way is to always have all threads acquire locks in the exact same
order.  If, for example, you lock variables <code class="inline"><span class="i">$x</span></code>
, <code class="inline"><span class="i">$y</span></code>
, and <code class="inline"><span class="i">$z</span></code>
, always lock
<code class="inline"><span class="i">$x</span></code>
 before <code class="inline"><span class="i">$y</span></code>
, and <code class="inline"><span class="i">$y</span></code>
 before <code class="inline"><span class="i">$z</span></code>
.  It's also best to hold on to locks for
as short a period of time to minimize the risks of deadlock.</p>
<p>The other synchronization primitives described below can suffer from
similar problems.</p>
<a name="Queues%3a-Passing-Data-Around"></a><h2>Queues: Passing Data Around</h2>
<p>A queue is a special thread-safe object that lets you put data in one
end and take it out the other without having to worry about
synchronization issues.  They're pretty straightforward, and look like
this:</p>
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/use.html">use</a> <span class="w">threads</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/use.html">use</a> <span class="w">Thread::Queue</span><span class="sc">;</span></li><li></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$DataQueue</span> = <span class="w">Thread::Queue</span><span class="w">-&gt;new</span><span class="s">(</span><span class="s">)</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$thr</span> = <span class="w">threads</span><span class="w">-&gt;create</span><span class="s">(</span><a class="l_k" href="functions/sub.html">sub</a> <span class="s">{</span></li><li>        while <span class="s">(</span><a class="l_k" href="functions/my.html">my</a> <span class="i">$DataElement</span> = <span class="i">$DataQueue</span><span class="i">-&gt;dequeue</span><span class="s">(</span><span class="s">)</span><span class="s">)</span> <span class="s">{</span></li><li>            <a class="l_k" href="functions/print.html">print</a><span class="s">(</span><span class="q">&quot;Popped $DataElement off the queue\n&quot;</span><span class="s">)</span><span class="sc">;</span></li><li>        <span class="s">}</span></li><li>    <span class="s">}</span><span class="s">)</span><span class="sc">;</span></li><li></li><li>    <span class="i">$DataQueue</span><span class="i">-&gt;enqueue</span><span class="s">(</span><span class="n">12</span><span class="s">)</span><span class="sc">;</span></li><li>    <span class="i">$DataQueue</span><span class="i">-&gt;enqueue</span><span class="s">(</span><span class="q">&quot;A&quot;</span><span class="cm">,</span> <span class="q">&quot;B&quot;</span><span class="cm">,</span> <span class="q">&quot;C&quot;</span><span class="s">)</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/sleep.html">sleep</a><span class="s">(</span><span class="n">10</span><span class="s">)</span><span class="sc">;</span></li><li>    <span class="i">$DataQueue</span><span class="i">-&gt;enqueue</span><span class="s">(</span><a class="l_k" href="functions/undef.html">undef</a><span class="s">)</span><span class="sc">;</span></li><li>    <span class="i">$thr</span><span class="i">-&gt;join</span><span class="s">(</span><span class="s">)</span><span class="sc">;</span></li></ol></pre><p>You create the queue with <code class="inline"><span class="w">Thread::Queue</span><span class="w">-&gt;new</span><span class="s">(</span><span class="s">)</span></code>
.  Then you can
add lists of scalars onto the end with <code class="inline"><span class="i">enqueue</span><span class="s">(</span><span class="s">)</span></code>
, and pop scalars off
the front of it with <code class="inline"><span class="i">dequeue</span><span class="s">(</span><span class="s">)</span></code>
.  A queue has no fixed size, and can grow
as needed to hold everything pushed on to it.</p>
<p>If a queue is empty, <code class="inline"><span class="i">dequeue</span><span class="s">(</span><span class="s">)</span></code>
 blocks until another thread enqueues
something.  This makes queues ideal for event loops and other
communications between threads.</p>
<a name="Semaphores%3a-Synchronizing-Data-Access"></a><h2>Semaphores: Synchronizing Data Access</h2>
<p>Semaphores are a kind of generic locking mechanism. In their most basic
form, they behave very much like lockable scalars, except that they
can't hold data, and that they must be explicitly unlocked. In their
advanced form, they act like a kind of counter, and can allow multiple
threads to have the <i>lock</i> at any one time.</p>
<a name="Basic-semaphores"></a><h2>Basic semaphores</h2>
<p>Semaphores have two methods, <code class="inline"><span class="i">down</span><span class="s">(</span><span class="s">)</span></code>
 and <code class="inline"><span class="i">up</span><span class="s">(</span><span class="s">)</span></code>
: <code class="inline"><span class="i">down</span><span class="s">(</span><span class="s">)</span></code>
 decrements the resource
count, while <code class="inline"><span class="i">up</span><span class="s">(</span><span class="s">)</span></code>
 increments it. Calls to <code class="inline"><span class="i">down</span><span class="s">(</span><span class="s">)</span></code>
 will block if the
semaphore's current count would decrement below zero.  This program
gives a quick demonstration:</p>
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/use.html">use</a> <span class="w">threads</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/use.html">use</a> <span class="w">Thread::Semaphore</span><span class="sc">;</span></li><li></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$semaphore</span> = <span class="w">Thread::Semaphore</span><span class="w">-&gt;new</span><span class="s">(</span><span class="s">)</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$GlobalVariable</span> <span class="co">:</span><span class="w">shared</span> = <span class="n">0</span><span class="sc">;</span></li><li></li><li>    <span class="i">$thr1</span> = <span class="w">threads</span><span class="w">-&gt;create</span><span class="s">(</span>\<span class="i">&amp;sample_sub</span><span class="cm">,</span> <span class="n">1</span><span class="s">)</span><span class="sc">;</span></li><li>    <span class="i">$thr2</span> = <span class="w">threads</span><span class="w">-&gt;create</span><span class="s">(</span>\<span class="i">&amp;sample_sub</span><span class="cm">,</span> <span class="n">2</span><span class="s">)</span><span class="sc">;</span></li><li>    <span class="i">$thr3</span> = <span class="w">threads</span><span class="w">-&gt;create</span><span class="s">(</span>\<span class="i">&amp;sample_sub</span><span class="cm">,</span> <span class="n">3</span><span class="s">)</span><span class="sc">;</span></li><li></li><li><a name="sample_sub"></a>    sub <span class="m">sample_sub</span> <span class="s">{</span></li><li>        <a class="l_k" href="functions/my.html">my</a> <span class="i">$SubNumber</span> = <a class="l_k" href="functions/shift.html">shift</a><span class="s">(</span><span class="i">@_</span><span class="s">)</span><span class="sc">;</span></li><li>        <a class="l_k" href="functions/my.html">my</a> <span class="i">$TryCount</span> = <span class="n">10</span><span class="sc">;</span></li><li>        <a class="l_k" href="functions/my.html">my</a> <span class="i">$LocalCopy</span><span class="sc">;</span></li><li>        <a class="l_k" href="functions/sleep.html">sleep</a><span class="s">(</span><span class="n">1</span><span class="s">)</span><span class="sc">;</span></li><li>        <a class="l_k" href="functions/while.html">while</a> <span class="s">(</span><span class="i">$TryCount</span>--<span class="s">)</span> <span class="s">{</span></li><li>            <span class="i">$semaphore</span><span class="i">-&gt;down</span><span class="s">(</span><span class="s">)</span><span class="sc">;</span></li><li>            <span class="i">$LocalCopy</span> = <span class="i">$GlobalVariable</span><span class="sc">;</span></li><li>            <a class="l_k" href="functions/print.html">print</a><span class="s">(</span><span class="q">&quot;$TryCount tries left for sub $SubNumber &quot;</span></li><li>                 .<span class="q">&quot;(\$GlobalVariable is $GlobalVariable)\n&quot;</span><span class="s">)</span><span class="sc">;</span></li><li>            <a class="l_k" href="functions/sleep.html">sleep</a><span class="s">(</span><span class="n">2</span><span class="s">)</span><span class="sc">;</span></li><li>            <span class="i">$LocalCopy</span>++<span class="sc">;</span></li><li>            <span class="i">$GlobalVariable</span> = <span class="i">$LocalCopy</span><span class="sc">;</span></li><li>            <span class="i">$semaphore</span><span class="i">-&gt;up</span><span class="s">(</span><span class="s">)</span><span class="sc">;</span></li><li>        <span class="s">}</span></li><li>    <span class="s">}</span></li><li></li><li>    <span class="i">$thr1</span><span class="i">-&gt;join</span><span class="s">(</span><span class="s">)</span><span class="sc">;</span></li><li>    <span class="i">$thr2</span><span class="i">-&gt;join</span><span class="s">(</span><span class="s">)</span><span class="sc">;</span></li><li>    <span class="i">$thr3</span><span class="i">-&gt;join</span><span class="s">(</span><span class="s">)</span><span class="sc">;</span></li></ol></pre><p>The three invocations of the subroutine all operate in sync.  The
semaphore, though, makes sure that only one thread is accessing the
global variable at once.</p>
<a name="Advanced-Semaphores"></a><h2>Advanced Semaphores</h2>
<p>By default, semaphores behave like locks, letting only one thread
<code class="inline"><span class="i">down</span><span class="s">(</span><span class="s">)</span></code>
 them at a time.  However, there are other uses for semaphores.</p>
<p>Each semaphore has a counter attached to it. By default, semaphores are
created with the counter set to one, <code class="inline"><span class="i">down</span><span class="s">(</span><span class="s">)</span></code>
 decrements the counter by
one, and <code class="inline"><span class="i">up</span><span class="s">(</span><span class="s">)</span></code>
 increments by one. However, we can override any or all
of these defaults simply by passing in different values:</p>
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/use.html">use</a> <span class="w">threads</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/use.html">use</a> <span class="w">Thread::Semaphore</span><span class="sc">;</span></li><li></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$semaphore</span> = <span class="w">Thread::Semaphore</span><span class="w">-&gt;new</span><span class="s">(</span><span class="n">5</span><span class="s">)</span><span class="sc">;</span></li><li>                    <span class="c"># Creates a semaphore with the counter set to five</span></li><li></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$thr1</span> = <span class="w">threads</span><span class="w">-&gt;create</span><span class="s">(</span>\<span class="i">&amp;sub1</span><span class="s">)</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$thr2</span> = <span class="w">threads</span><span class="w">-&gt;create</span><span class="s">(</span>\<span class="i">&amp;sub1</span><span class="s">)</span><span class="sc">;</span></li><li></li><li><a name="sub1"></a>    sub <span class="m">sub1</span> <span class="s">{</span></li><li>        <span class="i">$semaphore</span><span class="i">-&gt;down</span><span class="s">(</span><span class="n">5</span><span class="s">)</span><span class="sc">;</span> <span class="c"># Decrements the counter by five</span></li><li>        <span class="c"># Do stuff here</span></li><li>        <span class="i">$semaphore</span><span class="i">-&gt;up</span><span class="s">(</span><span class="n">5</span><span class="s">)</span><span class="sc">;</span> <span class="c"># Increment the counter by five</span></li><li>    <span class="s">}</span></li><li></li><li>    <span class="i">$thr1</span><span class="i">-&gt;detach</span><span class="s">(</span><span class="s">)</span><span class="sc">;</span></li><li>    <span class="i">$thr2</span><span class="i">-&gt;detach</span><span class="s">(</span><span class="s">)</span><span class="sc">;</span></li></ol></pre><p>If <code class="inline"><span class="i">down</span><span class="s">(</span><span class="s">)</span></code>
 attempts to decrement the counter below zero, it blocks until
the counter is large enough.  Note that while a semaphore can be created
with a starting count of zero, any <code class="inline"><span class="i">up</span><span class="s">(</span><span class="s">)</span></code>
 or <code class="inline"><span class="i">down</span><span class="s">(</span><span class="s">)</span></code>
 always changes the
counter by at least one, and so <code class="inline"><span class="i">$semaphore</span><span class="i">-&gt;down</span><span class="s">(</span><span class="n">0</span><span class="s">)</span></code>
 is the same as
<code class="inline"><span class="i">$semaphore</span><span class="i">-&gt;down</span><span class="s">(</span><span class="n">1</span><span class="s">)</span></code>
.</p>
<p>The question, of course, is why would you do something like this? Why
create a semaphore with a starting count that's not one, or why
decrement or increment it by more than one? The answer is resource
availability.  Many resources that you want to manage access for can be
safely used by more than one thread at once.</p>
<p>For example, let's take a GUI driven program.  It has a semaphore that
it uses to synchronize access to the display, so only one thread is
ever drawing at once.  Handy, but of course you don't want any thread
to start drawing until things are properly set up.  In this case, you
can create a semaphore with a counter set to zero, and up it when
things are ready for drawing.</p>
<p>Semaphores with counters greater than one are also useful for
establishing quotas.  Say, for example, that you have a number of
threads that can do I/O at once.  You don't want all the threads
reading or writing at once though, since that can potentially swamp
your I/O channels, or deplete your process's quota of filehandles.  You
can use a semaphore initialized to the number of concurrent I/O
requests (or open files) that you want at any one time, and have your
threads quietly block and unblock themselves.</p>
<p>Larger increments or decrements are handy in those cases where a
thread needs to check out or return a number of resources at once.</p>
<a name="Waiting-for-a-Condition"></a><h2>Waiting for a Condition</h2>
<p>The functions <code class="inline"><span class="i">cond_wait</span><span class="s">(</span><span class="s">)</span></code>
 and <code class="inline"><span class="i">cond_signal</span><span class="s">(</span><span class="s">)</span></code>

can be used in conjunction with locks to notify
co-operating threads that a resource has become available. They are
very similar in use to the functions found in <code class="inline"><span class="w">pthreads</span></code>
. However
for most purposes, queues are simpler to use and more intuitive. See
<a href="threads/shared.html">threads::shared</a> for more details.</p>
<a name="Giving-up-control"></a><h2>Giving up control</h2>
<p>There are times when you may find it useful to have a thread
explicitly give up the CPU to another thread.  You may be doing something
processor-intensive and want to make sure that the user-interface thread
gets called frequently.  Regardless, there are times that you might want
a thread to give up the processor.</p>
<p>Perl's threading package provides the <code class="inline"><span class="i">yield</span><span class="s">(</span><span class="s">)</span></code>
 function that does
this. <code class="inline"><span class="i">yield</span><span class="s">(</span><span class="s">)</span></code>
 is pretty straightforward, and works like this:</p>
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/use.html">use</a> <span class="w">threads</span><span class="sc">;</span></li><li></li><li><a name="loop"></a>    sub <span class="m">loop</span> <span class="s">{</span></li><li>        <a class="l_k" href="functions/my.html">my</a> <span class="i">$thread</span> = <a class="l_k" href="functions/shift.html">shift</a><span class="sc">;</span></li><li>        <a class="l_k" href="functions/my.html">my</a> <span class="i">$foo</span> = <span class="n">50</span><span class="sc">;</span></li><li>        while<span class="s">(</span><span class="i">$foo</span>--<span class="s">)</span> <span class="s">{</span> <a class="l_k" href="functions/print.html">print</a><span class="s">(</span><span class="q">&quot;In thread $thread\n&quot;</span><span class="s">)</span><span class="sc">;</span> <span class="s">}</span></li><li>        <span class="w">threads</span><span class="w">-&gt;yield</span><span class="s">(</span><span class="s">)</span><span class="sc">;</span></li><li>        <span class="i">$foo</span> = <span class="n">50</span><span class="sc">;</span></li><li>        while<span class="s">(</span><span class="i">$foo</span>--<span class="s">)</span> <span class="s">{</span> <a class="l_k" href="functions/print.html">print</a><span class="s">(</span><span class="q">&quot;In thread $thread\n&quot;</span><span class="s">)</span><span class="sc">;</span> <span class="s">}</span></li><li>    <span class="s">}</span></li><li></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$thr1</span> = <span class="w">threads</span><span class="w">-&gt;create</span><span class="s">(</span>\<span class="i">&amp;loop</span><span class="cm">,</span> <span class="q">&#39;first&#39;</span><span class="s">)</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$thr2</span> = <span class="w">threads</span><span class="w">-&gt;create</span><span class="s">(</span>\<span class="i">&amp;loop</span><span class="cm">,</span> <span class="q">&#39;second&#39;</span><span class="s">)</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$thr3</span> = <span class="w">threads</span><span class="w">-&gt;create</span><span class="s">(</span>\<span class="i">&amp;loop</span><span class="cm">,</span> <span class="q">&#39;third&#39;</span><span class="s">)</span><span class="sc">;</span></li></ol></pre><p>It is important to remember that <code class="inline"><span class="i">yield</span><span class="s">(</span><span class="s">)</span></code>
 is only a hint to give up the CPU,
it depends on your hardware, OS and threading libraries what actually happens.
<b>On many operating systems, yield() is a no-op.</b>  Therefore it is important
to note that one should not build the scheduling of the threads around
<code class="inline"><span class="i">yield</span><span class="s">(</span><span class="s">)</span></code>
 calls. It might work on your platform but it won't work on another
platform.</p>
<a name="General-Thread-Utility-Routines"></a><h1>General Thread Utility Routines</h1>
<p>We've covered the workhorse parts of Perl's threading package, and
with these tools you should be well on your way to writing threaded
code and packages.  There are a few useful little pieces that didn't
really fit in anyplace else.</p>
<a name="What-Thread-Am-I-In%3f"></a><h2>What Thread Am I In?</h2>
<p>The <code class="inline"><span class="w">threads</span><span class="w">-&gt;self</span><span class="s">(</span><span class="s">)</span></code>
 class method provides your program with a way to
get an object representing the thread it's currently in.  You can use this
object in the same way as the ones returned from thread creation.</p>
<a name="Thread-IDs"></a><h2>Thread IDs</h2>
<p><code class="inline"><span class="i">tid</span><span class="s">(</span><span class="s">)</span></code>
 is a thread object method that returns the thread ID of the
thread the object represents.  Thread IDs are integers, with the main
thread in a program being 0.  Currently Perl assigns a unique TID to
every thread ever created in your program, assigning the first thread
to be created a TID of 1, and increasing the TID by 1 for each new
thread that's created.  When used as a class method, <code class="inline"><span class="w">threads</span><span class="w">-&gt;tid</span><span class="s">(</span><span class="s">)</span></code>

can be used by a thread to get its own TID.</p>
<a name="Are-These-Threads-The-Same%3f"></a><h2>Are These Threads The Same?</h2>
<p>The <code class="inline"><span class="i">equal</span><span class="s">(</span><span class="s">)</span></code>
 method takes two thread objects and returns true
if the objects represent the same thread, and false if they don't.</p>
<p>Thread objects also have an overloaded <code class="inline">==</code>
 comparison so that you can do
comparison on them as you would with normal objects.</p>
<a name="What-Threads-Are-Running%3f"></a><h2>What Threads Are Running?</h2>
<p><code class="inline"><span class="w">threads</span><span class="w">-&gt;list</span><span class="s">(</span><span class="s">)</span></code>
 returns a list of thread objects, one for each thread
that's currently running and not detached.  Handy for a number of things,
including cleaning up at the end of your program (from the main Perl thread,
of course):</p>
<pre class="verbatim"><ol><li>    <span class="c"># Loop through all the threads</span></li><li>    foreach <a class="l_k" href="functions/my.html">my</a> <span class="i">$thr</span> <span class="s">(</span><span class="w">threads</span><span class="w">-&gt;list</span><span class="s">(</span><span class="s">)</span><span class="s">)</span> <span class="s">{</span></li><li>        <span class="i">$thr</span><span class="i">-&gt;join</span><span class="s">(</span><span class="s">)</span><span class="sc">;</span></li><li>    <span class="s">}</span></li></ol></pre><p>If some threads have not finished running when the main Perl thread
ends, Perl will warn you about it and die, since it is impossible for Perl
to clean up itself while other threads are running.</p>
<p>NOTE:  The main Perl thread (thread 0) is in a <i>detached</i> state, and so
does not appear in the list returned by <code class="inline"><span class="w">threads</span><span class="w">-&gt;list</span><span class="s">(</span><span class="s">)</span></code>
.</p>
<a name="A-Complete-Example"></a><h1>A Complete Example</h1>
<p>Confused yet? It's time for an example program to show some of the
things we've covered.  This program finds prime numbers using threads.</p>
<pre class="verbatim"><ol><li>   <span class="n">1</span> <span class="c">#!/usr/bin/perl</span></li><li>   <span class="n">2</span> <span class="c"># prime-pthread, courtesy of Tom Christiansen</span></li><li>   <span class="n">3</span></li><li>   <span class="n">4</span> <a class="l_k" href="functions/use.html">use</a> <span class="w">strict</span><span class="sc">;</span></li><li>   <span class="n">5</span> <a class="l_k" href="functions/use.html">use</a> <span class="w">warnings</span><span class="sc">;</span></li><li>   <span class="n">6</span></li><li>   <span class="n">7</span> <a class="l_k" href="functions/use.html">use</a> <span class="w">threads</span><span class="sc">;</span></li><li>   <span class="n">8</span> <a class="l_k" href="functions/use.html">use</a> <span class="w">Thread::Queue</span><span class="sc">;</span></li><li>   <span class="n">9</span></li><li><a name="check_num"></a>  <span class="n">10</span> sub <span class="m">check_num</span> <span class="s">{</span></li><li>  <span class="n">11</span>     <a class="l_k" href="functions/my.html">my</a> <span class="s">(</span><span class="i">$upstream</span><span class="cm">,</span> <span class="i">$cur_prime</span><span class="s">)</span> = <span class="i">@_</span><span class="sc">;</span></li><li>  <span class="n">12</span>     <a class="l_k" href="functions/my.html">my</a> <span class="i">$kid</span><span class="sc">;</span></li><li>  <span class="n">13</span>     <a class="l_k" href="functions/my.html">my</a> <span class="i">$downstream</span> = <span class="w">Thread::Queue</span><span class="w">-&gt;new</span><span class="s">(</span><span class="s">)</span><span class="sc">;</span></li><li>  <span class="n">14</span>     <a class="l_k" href="functions/while.html">while</a> <span class="s">(</span><a class="l_k" href="functions/my.html">my</a> <span class="i">$num</span> = <span class="i">$upstream</span><span class="i">-&gt;dequeue</span><span class="s">(</span><span class="s">)</span><span class="s">)</span> <span class="s">{</span></li><li>  <span class="n">15</span>         <a class="l_k" href="functions/next.html">next</a> <a class="l_k" href="functions/unless.html">unless</a> <span class="s">(</span><span class="i">$num</span> % <span class="i">$cur_prime</span><span class="s">)</span><span class="sc">;</span></li><li>  <span class="n">16</span>         <a class="l_k" href="functions/if.html">if</a> <span class="s">(</span><span class="i">$kid</span><span class="s">)</span> <span class="s">{</span></li><li>  <span class="n">17</span>             <span class="i">$downstream</span><span class="i">-&gt;enqueue</span><span class="s">(</span><span class="i">$num</span><span class="s">)</span><span class="sc">;</span></li><li>  <span class="n">18</span>         <span class="s">}</span> <a class="l_k" href="functions/else.html">else</a> <span class="s">{</span></li><li>  <span class="n">19</span>             <a class="l_k" href="functions/print.html">print</a><span class="s">(</span><span class="q">&quot;Found prime: $num\n&quot;</span><span class="s">)</span><span class="sc">;</span></li><li>  <span class="n">20</span>             <span class="i">$kid</span> = <span class="w">threads</span><span class="w">-&gt;create</span><span class="s">(</span>\<span class="i">&amp;check_num</span><span class="cm">,</span> <span class="i">$downstream</span><span class="cm">,</span> <span class="i">$num</span><span class="s">)</span><span class="sc">;</span></li><li>  <span class="n">21</span>             <a class="l_k" href="functions/if.html">if</a> <span class="s">(</span>! <span class="i">$kid</span><span class="s">)</span> <span class="s">{</span></li><li>  <span class="n">22</span>                 <a class="l_k" href="functions/warn.html">warn</a><span class="s">(</span><span class="q">&quot;Sorry.  Ran out of threads.\n&quot;</span><span class="s">)</span><span class="sc">;</span></li><li>  <span class="n">23</span>                 <a class="l_k" href="functions/last.html">last</a><span class="sc">;</span></li><li>  <span class="n">24</span>             <span class="s">}</span></li><li>  <span class="n">25</span>         <span class="s">}</span></li><li>  <span class="n">26</span>     <span class="s">}</span></li><li>  <span class="n">27</span>     <a class="l_k" href="functions/if.html">if</a> <span class="s">(</span><span class="i">$kid</span><span class="s">)</span> <span class="s">{</span></li><li>  <span class="n">28</span>         <span class="i">$downstream</span><span class="i">-&gt;enqueue</span><span class="s">(</span><a class="l_k" href="functions/undef.html">undef</a><span class="s">)</span><span class="sc">;</span></li><li>  <span class="n">29</span>         <span class="i">$kid</span><span class="i">-&gt;join</span><span class="s">(</span><span class="s">)</span><span class="sc">;</span></li><li>  <span class="n">30</span>     <span class="s">}</span></li><li>  <span class="n">31</span> <span class="s">}</span></li><li>  <span class="n">32</span></li><li>  <span class="n">33</span> <a class="l_k" href="functions/my.html">my</a> <span class="i">$stream</span> = <span class="w">Thread::Queue</span><span class="w">-&gt;new</span><span class="s">(</span><span class="n">3</span>..<span class="n">1000</span><span class="cm">,</span> <a class="l_k" href="functions/undef.html">undef</a><span class="s">)</span><span class="sc">;</span></li><li>  <span class="n">34</span> <span class="i">check_num</span><span class="s">(</span><span class="i">$stream</span><span class="cm">,</span> <span class="n">2</span><span class="s">)</span><span class="sc">;</span></li></ol></pre><p>This program uses the pipeline model to generate prime numbers.  Each
thread in the pipeline has an input queue that feeds numbers to be
checked, a prime number that it's responsible for, and an output queue
into which it funnels numbers that have failed the check.  If the thread
has a number that's failed its check and there's no child thread, then
the thread must have found a new prime number.  In that case, a new
child thread is created for that prime and stuck on the end of the
pipeline.</p>
<p>This probably sounds a bit more confusing than it really is, so let's
go through this program piece by piece and see what it does.  (For
those of you who might be trying to remember exactly what a prime
number is, it's a number that's only evenly divisible by itself and 1.)</p>
<p>The bulk of the work is done by the <code class="inline"><span class="i">check_num</span><span class="s">(</span><span class="s">)</span></code>
 subroutine, which
takes a reference to its input queue and a prime number that it's
responsible for.  After pulling in the input queue and the prime that
the subroutine is checking (line 11), we create a new queue (line 13)
and reserve a scalar for the thread that we're likely to create later
(line 12).</p>
<p>The while loop from line 14 to line 26 grabs a scalar off the input
queue and checks against the prime this thread is responsible
for.  Line 15 checks to see if there's a remainder when we divide the
number to be checked by our prime.  If there is one, the number
must not be evenly divisible by our prime, so we need to either pass
it on to the next thread if we've created one (line 17) or create a
new thread if we haven't.</p>
<p>The new thread creation is line 20.  We pass on to it a reference to
the queue we've created, and the prime number we've found.  In lines 21
through 24, we check to make sure that our new thread got created, and
if not, we stop checking any remaining numbers in the queue.</p>
<p>Finally, once the loop terminates (because we got a 0 or <code class="inline"><a class="l_k" href="functions/undef.html">undef</a></code> in the
queue, which serves as a note to terminate), we pass on the notice to our
child, and wait for it to exit if we've created a child (lines 27 and
30).</p>
<p>Meanwhile, back in the main thread, we first create a queue (line 33) and
queue up all the numbers from 3 to 1000 for checking, plus a termination
notice.  Then all we have to do to get the ball rolling is pass the queue
and the first prime to the <code class="inline"><span class="i">check_num</span><span class="s">(</span><span class="s">)</span></code>
 subroutine (line 34).</p>
<p>That's how it works.  It's pretty simple; as with many Perl programs,
the explanation is much longer than the program.</p>
<a name="Different-implementations-of-threads"></a><h1>Different implementations of threads</h1>
<p>Some background on thread implementations from the operating system
viewpoint.  There are three basic categories of threads: user-mode threads,
kernel threads, and multiprocessor kernel threads.</p>
<p>User-mode threads are threads that live entirely within a program and
its libraries.  In this model, the OS knows nothing about threads.  As
far as it's concerned, your process is just a process.</p>
<p>This is the easiest way to implement threads, and the way most OSes
start.  The big disadvantage is that, since the OS knows nothing about
threads, if one thread blocks they all do.  Typical blocking activities
include most system calls, most I/O, and things like <code class="inline"><a class="l_k" href="functions/sleep.html">sleep()</a></code>.</p>
<p>Kernel threads are the next step in thread evolution.  The OS knows
about kernel threads, and makes allowances for them.  The main
difference between a kernel thread and a user-mode thread is
blocking.  With kernel threads, things that block a single thread don't
block other threads.  This is not the case with user-mode threads,
where the kernel blocks at the process level and not the thread level.</p>
<p>This is a big step forward, and can give a threaded program quite a
performance boost over non-threaded programs.  Threads that block
performing I/O, for example, won't block threads that are doing other
things.  Each process still has only one thread running at once,
though, regardless of how many CPUs a system might have.</p>
<p>Since kernel threading can interrupt a thread at any time, they will
uncover some of the implicit locking assumptions you may make in your
program.  For example, something as simple as <code class="inline"><span class="i">$x</span> = <span class="i">$x</span> + <span class="n">2</span></code>
 can behave
unpredictably with kernel threads if <code class="inline"><span class="i">$x</span></code>
 is visible to other
threads, as another thread may have changed <code class="inline"><span class="i">$x</span></code>
 between the time it
was fetched on the right hand side and the time the new value is
stored.</p>
<p>Multiprocessor kernel threads are the final step in thread
support.  With multiprocessor kernel threads on a machine with multiple
CPUs, the OS may schedule two or more threads to run simultaneously on
different CPUs.</p>
<p>This can give a serious performance boost to your threaded program,
since more than one thread will be executing at the same time.  As a
tradeoff, though, any of those nagging synchronization issues that
might not have shown with basic kernel threads will appear with a
vengeance.</p>
<p>In addition to the different levels of OS involvement in threads,
different OSes (and different thread implementations for a particular
OS) allocate CPU cycles to threads in different ways.</p>
<p>Cooperative multitasking systems have running threads give up control
if one of two things happen.  If a thread calls a yield function, it
gives up control.  It also gives up control if the thread does
something that would cause it to block, such as perform I/O.  In a
cooperative multitasking implementation, one thread can starve all the
others for CPU time if it so chooses.</p>
<p>Preemptive multitasking systems interrupt threads at regular intervals
while the system decides which thread should run next.  In a preemptive
multitasking system, one thread usually won't monopolize the CPU.</p>
<p>On some systems, there can be cooperative and preemptive threads
running simultaneously. (Threads running with realtime priorities
often behave cooperatively, for example, while threads running at
normal priorities behave preemptively.)</p>
<p>Most modern operating systems support preemptive multitasking nowadays.</p>
<a name="Performance-considerations"></a><h1>Performance considerations</h1>
<p>The main thing to bear in mind when comparing Perl's <i>ithreads</i> to other threading
models is the fact that for each new thread created, a complete copy of
all the variables and data of the parent thread has to be taken. Thus,
thread creation can be quite expensive, both in terms of memory usage and
time spent in creation. The ideal way to reduce these costs is to have a
relatively short number of long-lived threads, all created fairly early
on (before the base thread has accumulated too much data). Of course, this
may not always be possible, so compromises have to be made. However, after
a thread has been created, its performance and extra memory usage should
be little different than ordinary code.</p>
<p>Also note that under the current implementation, shared variables
use a little more memory and are a little slower than ordinary variables.</p>
<a name="Process-scope-Changes"></a><h1>Process-scope Changes</h1>
<p>Note that while threads themselves are separate execution threads and
Perl data is thread-private unless explicitly shared, the threads can
affect process-scope state, affecting all the threads.</p>
<p>The most common example of this is changing the current working
directory using <code class="inline"><a class="l_k" href="functions/chdir.html">chdir()</a></code>.  One thread calls <code class="inline"><a class="l_k" href="functions/chdir.html">chdir()</a></code>, and the working
directory of all the threads changes.</p>
<p>Even more drastic example of a process-scope change is <code class="inline"><a class="l_k" href="functions/chroot.html">chroot()</a></code>:
the root directory of all the threads changes, and no thread can
undo it (as opposed to <code class="inline"><a class="l_k" href="functions/chdir.html">chdir()</a></code>).</p>
<p>Further examples of process-scope changes include <code class="inline"><a class="l_k" href="functions/umask.html">umask()</a></code> and
changing uids and gids.</p>
<p>Thinking of mixing <code class="inline"><a class="l_k" href="functions/fork.html">fork()</a></code> and threads?  Please lie down and wait
until the feeling passes.  Be aware that the semantics of <code class="inline"><a class="l_k" href="functions/fork.html">fork()</a></code> vary
between platforms.  For example, some Unix systems copy all the current
threads into the child process, while others only copy the thread that
called <code class="inline"><a class="l_k" href="functions/fork.html">fork()</a></code>. You have been warned!</p>
<p>Similarly, mixing signals and threads may be problematic.
Implementations are platform-dependent, and even the POSIX
semantics may not be what you expect (and Perl doesn't even
give you the full POSIX API).  For example, there is no way to
guarantee that a signal sent to a multi-threaded Perl application
will get intercepted by any particular thread.  (However, a recently
added feature does provide the capability to send signals between
threads.  See <a href="threads.html#THREAD-SIGNALLING">THREAD SIGNALLING in threads</a> for more details.)</p>
<a name="Thread-Safety-of-System-Libraries"></a><h1>Thread-Safety of System Libraries</h1>
<p>Whether various library calls are thread-safe is outside the control
of Perl.  Calls often suffering from not being thread-safe include:
<code class="inline"><a class="l_k" href="functions/localtime.html">localtime()</a></code>, <code class="inline"><a class="l_k" href="functions/gmtime.html">gmtime()</a></code>,  functions fetching user, group and
network information (such as <code class="inline"><a class="l_k" href="functions/getgrent.html">getgrent()</a></code>, <code class="inline"><a class="l_k" href="functions/gethostent.html">gethostent()</a></code>,
<code class="inline"><a class="l_k" href="functions/getnetent.html">getnetent()</a></code> and so on), <code class="inline"><a class="l_k" href="functions/readdir.html">readdir()</a></code>, <code class="inline"><a class="l_k" href="functions/rand.html">rand()</a></code>, and <code class="inline"><a class="l_k" href="functions/srand.html">srand()</a></code>. In
general, calls that depend on some global external state.</p>
<p>If the system Perl is compiled in has thread-safe variants of such
calls, they will be used.  Beyond that, Perl is at the mercy of
the thread-safety or -unsafety of the calls.  Please consult your
C library call documentation.</p>
<p>On some platforms the thread-safe library interfaces may fail if the
result buffer is too small (for example the user group databases may
be rather large, and the reentrant interfaces may have to carry around
a full snapshot of those databases).  Perl will start with a small
buffer, but keep retrying and growing the result buffer
until the result fits.  If this limitless growing sounds bad for
security or memory consumption reasons you can recompile Perl with
<code class="inline"><span class="w">PERL_REENTRANT_MAXSIZE</span></code>
 defined to the maximum number of bytes you will
allow.</p>
<a name="Conclusion"></a><h1>Conclusion</h1>
<p>A complete thread tutorial could fill a book (and has, many times),
but with what we've covered in this introduction, you should be well
on your way to becoming a threaded Perl expert.</p>
<a name="SEE-ALSO"></a><h1>SEE ALSO</h1>
<p>Annotated POD for <a href="threads.html">threads</a>:
<a href="http://annocpan.org/?mode=search&amp;field=Module&amp;name=threads">http://annocpan.org/?mode=search&amp;field=Module&amp;name=threads</a></p>
<p>Latest version of <a href="threads.html">threads</a> on CPAN:
<a href="http://search.cpan.org/search?module=threads">http://search.cpan.org/search?module=threads</a></p>
<p>Annotated POD for <a href="threads/shared.html">threads::shared</a>:
<a href="http://annocpan.org/?mode=search&amp;field=Module&amp;name=threads%3A%3Ashared">http://annocpan.org/?mode=search&amp;field=Module&amp;name=threads%3A%3Ashared</a></p>
<p>Latest version of <a href="threads/shared.html">threads::shared</a> on CPAN:
<a href="http://search.cpan.org/search?module=threads%3A%3Ashared">http://search.cpan.org/search?module=threads%3A%3Ashared</a></p>
<p>Perl threads mailing list:
<a href="http://lists.perl.org/list/ithreads.html">http://lists.perl.org/list/ithreads.html</a></p>
<a name="Bibliography"></a><h1>Bibliography</h1>
<p>Here's a short bibliography courtesy of J&#xfc;rgen Christoffel:</p>
<a name="Introductory-Texts"></a><h2>Introductory Texts</h2>
<p>Birrell, Andrew D. An Introduction to Programming with
Threads. Digital Equipment Corporation, 1989, DEC-SRC Research Report
#35 online as
<a href="ftp://ftp.dec.com/pub/DEC/SRC/research-reports/SRC-035.pdf">ftp://ftp.dec.com/pub/DEC/SRC/research-reports/SRC-035.pdf</a>
(highly recommended)</p>
<p>Robbins, Kay. A., and Steven Robbins. Practical Unix Programming: A
Guide to Concurrency, Communication, and
Multithreading. Prentice-Hall, 1996.</p>
<p>Lewis, Bill, and Daniel J. Berg. Multithreaded Programming with
Pthreads. Prentice Hall, 1997, ISBN 0-13-443698-9 (a well-written
introduction to threads).</p>
<p>Nelson, Greg (editor). Systems Programming with Modula-3.  Prentice
Hall, 1991, ISBN 0-13-590464-1.</p>
<p>Nichols, Bradford, Dick Buttlar, and Jacqueline Proulx Farrell.
Pthreads Programming. O'Reilly &amp; Associates, 1996, ISBN 156592-115-1
(covers POSIX threads).</p>
<a name="OS-Related-References"></a><h2>OS-Related References</h2>
<p>Boykin, Joseph, David Kirschen, Alan Langerman, and Susan
LoVerso. Programming under Mach. Addison-Wesley, 1994, ISBN
0-201-52739-1.</p>
<p>Tanenbaum, Andrew S. Distributed Operating Systems. Prentice Hall,
1995, ISBN 0-13-219908-4 (great textbook).</p>
<p>Silberschatz, Abraham, and Peter B. Galvin. Operating System Concepts,
4th ed. Addison-Wesley, 1995, ISBN 0-201-59292-4</p>
<a name="Other-References"></a><h2>Other References</h2>
<p>Arnold, Ken and James Gosling. The Java Programming Language, 2nd
ed. Addison-Wesley, 1998, ISBN 0-201-31006-6.</p>
<p>comp.programming.threads FAQ,
<a href="http://www.serpentine.com/~bos/threads-faq/">http://www.serpentine.com/~bos/threads-faq/</a></p>
<p>Le Sergent, T. and B. Berthomieu. "Incremental MultiThreaded Garbage
Collection on Virtually Shared Memory Architectures" in Memory
Management: Proc. of the International Workshop IWMM 92, St. Malo,
France, September 1992, Yves Bekkers and Jacques Cohen, eds. Springer,
1992, ISBN 3540-55940-X (real-life thread applications).</p>
<p>Artur Bergman, "Where Wizards Fear To Tread", June 11, 2002,
<a href="http://www.perl.com/pub/a/2002/06/11/threads.html">http://www.perl.com/pub/a/2002/06/11/threads.html</a></p>
<a name="Acknowledgements"></a><h1>Acknowledgements</h1>
<p>Thanks (in no particular order) to Chaim Frenkel, Steve Fink, Gurusamy
Sarathy, Ilya Zakharevich, Benjamin Sugars, J&#xfc;rgen Christoffel, Joshua
Pritikin, and Alan Burlison, for their help in reality-checking and
polishing this article.  Big thanks to Tom Christiansen for his rewrite
of the prime number generator.</p>
<a name="AUTHOR"></a><h1>AUTHOR</h1>
<p>Dan Sugalski &lt;dan@sidhe.org&lt;gt&gt;</p>
<p>Slightly modified by Arthur Bergman to fit the new thread model/module.</p>
<p>Reworked slightly by J&#xf6;rg Walter &lt;jwalt@cpan.org&lt;gt&gt; to be more concise
about thread-safety of Perl code.</p>
<p>Rearranged slightly by Elizabeth Mattijsen &lt;liz@dijkmat.nl&lt;gt&gt; to put
less emphasis on yield().</p>
<a name="Copyrights"></a><h1>Copyrights</h1>
<p>The original version of this article originally appeared in The Perl
Journal #10, and is copyright 1998 The Perl Journal. It appears courtesy
of Jon Orwant and The Perl Journal.  This document may be distributed
under the same terms as Perl itself.</p>




  <div id="page_index" class="hud_container">
    <div id="page_index_header" class="hud_header">
      <div id="page_index_close" class="hud_close"><a href="#" onClick="pageIndex.hide();return false;"></a></div>
      <div id="page_index_title" class="hud_title"><span class="hud_span_top">Page index</span></div>
      <div id="page_index_topright" class="hud_topright"></div>
    </div>
    <div id="page_index_content" class="hud_content">
      <ul><li><a href="#NAME">NAME</a><li><a href="#DESCRIPTION">DESCRIPTION</a><li><a href="#What-Is-A-Thread-Anyway%3f">What Is A Thread Anyway?</a><li><a href="#Threaded-Program-Models">Threaded Program Models</a><ul><li><a href="#Boss%2fWorker">Boss/Worker</a><li><a href="#Work-Crew">Work Crew</a><li><a href="#Pipeline">Pipeline</a></ul><li><a href="#What-kind-of-threads-are-Perl-threads%3f">What kind of threads are Perl threads?</a><li><a href="#Thread-Safe-Modules">Thread-Safe Modules</a><li><a href="#Thread-Basics">Thread Basics</a><ul><li><a href="#Basic-Thread-Support">Basic Thread Support</a><li><a href="#A-Note-about-the-Examples">A Note about the Examples</a><li><a href="#Creating-Threads">Creating Threads</a><li><a href="#Waiting-For-A-Thread-To-Exit">Waiting For A Thread To Exit</a><li><a href="#Ignoring-A-Thread">Ignoring A Thread</a><li><a href="#Process-and-Thread-Termination">Process and Thread Termination</a></ul><li><a href="#Threads-And-Data">Threads And Data</a><ul><li><a href="#Shared-And-Unshared-Data">Shared And Unshared Data</a><li><a href="#Thread-Pitfalls%3a-Races">Thread Pitfalls: Races</a></ul><li><a href="#Synchronization-and-control">Synchronization and control</a><ul><li><a href="#Controlling-access%3a-lock()">Controlling access: lock()</a><li><a href="#A-Thread-Pitfall%3a-Deadlocks">A Thread Pitfall: Deadlocks</a><li><a href="#Queues%3a-Passing-Data-Around">Queues: Passing Data Around</a><li><a href="#Semaphores%3a-Synchronizing-Data-Access">Semaphores: Synchronizing Data Access</a><li><a href="#Basic-semaphores">Basic semaphores</a><li><a href="#Advanced-Semaphores">Advanced Semaphores</a><li><a href="#Waiting-for-a-Condition">Waiting for a Condition</a><li><a href="#Giving-up-control">Giving up control</a></ul><li><a href="#General-Thread-Utility-Routines">General Thread Utility Routines</a><ul><li><a href="#What-Thread-Am-I-In%3f">What Thread Am I In?</a><li><a href="#Thread-IDs">Thread IDs</a><li><a href="#Are-These-Threads-The-Same%3f">Are These Threads The Same?</a><li><a href="#What-Threads-Are-Running%3f">What Threads Are Running?</a></ul><li><a href="#A-Complete-Example">A Complete Example</a><li><a href="#Different-implementations-of-threads">Different implementations of threads</a><li><a href="#Performance-considerations">Performance considerations</a><li><a href="#Process-scope-Changes">Process-scope Changes</a><li><a href="#Thread-Safety-of-System-Libraries">Thread-Safety of System Libraries</a><li><a href="#Conclusion">Conclusion</a><li><a href="#SEE-ALSO">SEE ALSO</a><li><a href="#Bibliography">Bibliography</a><ul><li><a href="#Introductory-Texts">Introductory Texts</a><li><a href="#OS-Related-References">OS-Related References</a><li><a href="#Other-References">Other References</a></ul><li><a href="#Acknowledgements">Acknowledgements</a><li><a href="#AUTHOR">AUTHOR</a><li><a href="#Copyrights">Copyrights</a></ul>
    </div>
    <div id="page_index_footer" class="hud_footer">
      <div id="page_index_bottomleft" class="hud_bottomleft"></div>
      <div id="page_index_bottom" class="hud_bottom"><span class="hud_span_bottom"></span></div>
      <div id="page_index_resize" class="hud_resize"></div>
    </div>
  </div>


	    &nbsp;
          </div>
          <div id="content_footer">
          </div>
        </div>
        <div class="clear"></div>
      </div>
      
    <div id="footer">
      <div id="footer_content">
        <div id="footer_strapline">
          perldoc.perl.org - Official documentation for the Perl programming language
        </div>
        <div id="footer_links">
          <div id="address">
            <p class="name">Contact details</p>
            <p class="address">
	      Site maintained by <a href="mailto:jj@jonallen.info">Jon Allen (JJ)</a><br>
	    </p>
            <p class="contact">
              Documentation maintained by the <a href="http://lists.cpan.org/showlist.cgi?name=perl5-porters">Perl 5 Porters</a>
            </p>
          </div>
          <ul class="f1">
            <li>Manual
              <ul class="f2">
                <li><a href="index-overview.html">Overview</a>
                <li><a href="index-tutorials.html">Tutorials</a>
                <li><a href="index-faq.html">FAQs</a>
                <li><a href="index-history.html">Changes</a>
              </ul>
            <li>Reference
              <ul class="f2">
                <li><a href="index-language.html">Language</a>
                <li><a href="index-functions.html">Functions</a>
                <li><a href="perlop.html">Operators</a>
                <li><a href="perlvar.html">Variables</a>
              </ul>
            <li>Modules
              <ul class="f2">
                <li><a href="index-modules-A.html">Modules</a>
                <li><a href="index-pragmas.html">Pragmas</a>
                <li><a href="index-utilities.html">Utilities</a>
              </ul>
            <li>Misc
              <ul class="f2">
                <li><a href="index-licence.html">License</a>
                <li><a href="index-internals.html">Internals</a>
                <li><a href="index-platforms.html">Platforms</a>
              </ul>          </ul>
          <div class="clear"></div>
        </div>
      </div>
      <div id="footer_end">
      </div>
    </div>
      
    </div>
      <script language="JavaScript" type="text/javascript" src="static/exploreperl.js"></script>
      <script language="JavaScript" src="static/combined-20100403.js" type="text/javascript"></script>
<script language="JavaScript" type="text/javascript">
  perldoc.setPath(0);
  perldoc.pageName    = 'perlthrtut';
  perldoc.pageAddress = 'perlthrtut.html';
  perldoc.contentPage = 1;
  explorePerl.render();
  explorePerl.addEvents('explore_anchor');
</script>
    
  </body>
</html>