This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Further discourage old Thread code; tell how to tell
[perl5.git] / lib / Thread.pm
CommitLineData
43d3ddbe
JH
1package Thread;
2
3$VERSION = '2.00';
4
4038bebf
JH
5use strict;
6
7our $ithreads;
8our $othreads;
9
43d3ddbe
JH
10BEGIN {
11 use Config;
4038bebf
JH
12 $ithreads = $Config{useithreads};
13 $othreads = $Config{use5005threads};
43d3ddbe
JH
14}
15
16require Exporter;
17use XSLoader ();
4038bebf 18our($VERSION, @ISA, @EXPORT, @EXPORT_OK);
43d3ddbe
JH
19
20@ISA = qw(Exporter);
21
22BEGIN {
23 if ($ithreads) {
24 @EXPORT = qw(share cond_wait cond_broadcast cond_signal unlock)
25 } elsif ($othreads) {
26 @EXPORT_OK = qw(cond_signal cond_broadcast cond_wait);
27 }
28 push @EXPORT_OK, qw(async yield);
29}
30
31=head1 NAME
32
33Thread - manipulate threads in Perl
34
35=head1 CAVEAT
36
37Perl has two thread models.
38
39In Perl 5.005 the thread model was that all data is implicitly shared
40and shared access to data has to be explicitly synchronized.
41This model is called "5005threads".
42
43In Perl 5.6 a new model was introduced in which all is was thread
44local and shared access to data has to be explicitly declared.
45This model is called "ithreads", for "interpreter threads".
46
47In Perl 5.6 the ithreads model was not available as a public API,
48only as an internal API that was available for extension writers,
49and to implement fork() emulation on Win32 platforms.
50
51In Perl 5.8 the ithreads model became available through the C<threads>
52module.
53
54Neither model is configured by default into Perl (except, as mentioned
8a20485c
JH
55above, in Win32 ithreads are always available.) You can see your
56Perl's threading configuration by running C<perl -V> and looking for
57the I<use...threads> variables, or inside script by C<use Config;>
58and testing for C<$Config{use5005threads}> and C<$Config{useithreads}>.
59
60For old code and interim backwards compatibility, the Thread module
61has been reworked to function as a frontend for both 5005threads and
62ithreads.
43d3ddbe 63
43d3ddbe
JH
64Note that the compatibility is not complete: because the data sharing
65models are directly opposed, anything to do with data sharing has to
66be thought differently. With the ithreads you must explicitly share()
67variables between the threads.
68
8a20485c
JH
69For new code the use of the C<Thread> module is discouraged and
70the direct use use of the C<threads> and C<threads::shared> modules
71is encouraged instead.
72
43d3ddbe
JH
73Finally, note that there are many known serious problems with the
745005threads, one of the least of which is that regular expression
75match variables like $1 are not threadsafe, that is, they easily get
76corrupted by competing threads. Other problems include more insidious
77data corruption and mysterious crashes. You are seriously urged to
78use ithreads instead.
79
80=head1 SYNOPSIS
81
82 use Thread;
83
84 my $t = Thread->new(\&start_sub, @start_args);
85
86 $result = $t->join;
87 $result = $t->eval;
88 $t->detach;
89
90 if ($t->done) {
91 $t->join;
92 }
93
94 if($t->equal($another_thread)) {
95 # ...
96 }
97
98 yield();
99
100 my $tid = Thread->self->tid;
101
102 lock($scalar);
103 lock(@array);
104 lock(%hash);
105
106 lock(\&sub); # not available with ithreads
107
108 $flags = $t->flags; # not available with ithreads
109
110 my @list = Thread->list; # not available with ithreads
111
112 unlock(...); # not available with the 5.005 threads
113
114 use Thread 'async';
115
116=head1 DESCRIPTION
117
118The C<Thread> module provides multithreading support for perl.
119
120=head1 FUNCTIONS
121
122=over 8
123
124=item $thread = Thread->new(\&start_sub)
125
126=item $thread = Thread->new(\&start_sub, LIST)
127
128C<new> starts a new thread of execution in the referenced subroutine. The
129optional list is passed as parameters to the subroutine. Execution
130continues in both the subroutine and the code after the C<new> call.
131
132C<Thread-&gt;new> returns a thread object representing the newly created
133thread.
134
135=item lock VARIABLE
136
137C<lock> places a lock on a variable until the lock goes out of scope
138(with ithreads you can also explicitly unlock()).
139
140If the variable is locked by another thread, the C<lock> call will
141block until it's available. C<lock> is recursive, so multiple calls
142to C<lock> are safe--the variable will remain locked until the
143outermost lock on the variable goes out of scope.
144
145Locks on variables only affect C<lock> calls--they do I<not> affect normal
146access to a variable. (Locks on subs are different, and covered in a bit.)
147If you really, I<really> want locks to block access, then go ahead and tie
148them to something and manage this yourself. This is done on purpose.
149While managing access to variables is a good thing, Perl doesn't force
150you out of its living room...
151
152If a container object, such as a hash or array, is locked, all the
153elements of that container are not locked. For example, if a thread
154does a C<lock @a>, any other thread doing a C<lock($a[12])> won't
155block.
156
157With 5005threads you may also C<lock> a sub, using C<lock &sub>.
158Any calls to that sub from another thread will block until the lock
159is released. This behaviour is not equivalent to declaring the sub
160with the C<locked> attribute. The C<locked> attribute serializes
161access to a subroutine, but allows different threads non-simultaneous
162access. C<lock &sub>, on the other hand, will not allow I<any> other
163thread access for the duration of the lock.
164
165Finally, C<lock> will traverse up references exactly I<one> level.
166C<lock(\$a)> is equivalent to C<lock($a)>, while C<lock(\\$a)> is not.
167
168=item async BLOCK;
169
170C<async> creates a thread to execute the block immediately following
171it. This block is treated as an anonymous sub, and so must have a
172semi-colon after the closing brace. Like C<Thread-&gt;new>, C<async>
173returns a thread object.
174
175=item Thread->self
176
177The C<Thread-E<gt>self> function returns a thread object that represents
178the thread making the C<Thread-E<gt>self> call.
179
180=item cond_wait VARIABLE
181
182The C<cond_wait> function takes a B<locked> variable as
183a parameter, unlocks the variable, and blocks until another thread
184does a C<cond_signal> or C<cond_broadcast> for that same locked
185variable. The variable that C<cond_wait> blocked on is relocked
186after the C<cond_wait> is satisfied. If there are multiple threads
187C<cond_wait>ing on the same variable, all but one will reblock waiting
188to reaquire the lock on the variable. (So if you're only using
189C<cond_wait> for synchronization, give up the lock as soon as
190possible.)
191
192=item cond_signal VARIABLE
193
194The C<cond_signal> function takes a locked variable as a parameter and
195unblocks one thread that's C<cond_wait>ing on that variable. If more than
196one thread is blocked in a C<cond_wait> on that variable, only one (and
197which one is indeterminate) will be unblocked.
198
199If there are no threads blocked in a C<cond_wait> on the variable,
200the signal is discarded.
201
202=item cond_broadcast VARIABLE
203
204The C<cond_broadcast> function works similarly to C<cond_signal>.
205C<cond_broadcast>, though, will unblock B<all> the threads that are
206blocked in a C<cond_wait> on the locked variable, rather than only
207one.
208
209=item yield
210
211The C<yield> function allows another thread to take control of the
212CPU. The exact results are implementation-dependent.
213
214=back
215
216=head1 METHODS
217
218=over 8
219
220=item join
221
222C<join> waits for a thread to end and returns any values the thread
223exited with. C<join> will block until the thread has ended, though
224it won't block if the thread has already terminated.
225
226If the thread being C<join>ed C<die>d, the error it died with will
227be returned at this time. If you don't want the thread performing
228the C<join> to die as well, you should either wrap the C<join> in
229an C<eval> or use the C<eval> thread method instead of C<join>.
230
231=item eval
232
233The C<eval> method wraps an C<eval> around a C<join>, and so waits for
234a thread to exit, passing along any values the thread might have returned.
235Errors, of course, get placed into C<$@>. (Not available with ithreads.)
236
237=item detach
238
239C<detach> tells a thread that it is never going to be joined i.e.
240that all traces of its existence can be removed once it stops running.
241Errors in detached threads will not be visible anywhere - if you want
242to catch them, you should use $SIG{__DIE__} or something like that.
243
244=item equal
245
246C<equal> tests whether two thread objects represent the same thread and
247returns true if they do.
248
249=item tid
250
251The C<tid> method returns the tid of a thread. The tid is
252a monotonically increasing integer assigned when a thread is
253created. The main thread of a program will have a tid of zero,
254while subsequent threads will have tids assigned starting with one.
255
256=item flags
257
258The C<flags> method returns the flags for the thread. This is the
259integer value corresponding to the internal flags for the thread,
260and the value may not be all that meaningful to you.
261(Not available with ithreads.)
262
263=item done
264
265The C<done> method returns true if the thread you're checking has
266finished, and false otherwise. (Not available with ithreads.)
267
268=back
269
270=head1 LIMITATIONS
271
272The sequence number used to assign tids is a simple integer, and no
273checking is done to make sure the tid isn't currently in use. If a
274program creates more than 2**32 - 1 threads in a single run, threads
275may be assigned duplicate tids. This limitation may be lifted in
276a future version of Perl.
277
278=head1 SEE ALSO
279
280L<threads::shared> (not available with 5005threads)
281
282L<attributes>, L<Thread::Queue>, L<Thread::Semaphore>,
283L<Thread::Specific> (not available with ithreads)
284
285=cut
286
287#
288# Methods
289#
290
291#
292# Exported functions
293#
294
295sub async (&) {
296 return Thread->new($_[0]);
297}
298
299sub eval {
300 return eval { shift->join; };
301}
302
303sub unimplemented {
304 print $_[0], " unimplemented with ",
305 $Config{useithreads} ? "ithreads" : "5005threads", "\n";
306
307}
308
309sub unimplement {
310 for my $m (@_) {
4038bebf 311 no strict 'refs';
43d3ddbe
JH
312 *{"Thread::$m"} = sub { unimplemented $m };
313 }
314}
315
316BEGIN {
317 if ($ithreads) {
318 XSLoader::load 'threads';
319 for my $m (qw(new join detach yield self tid equal)) {
4038bebf 320 no strict 'refs';
43d3ddbe
JH
321 *{"Thread::$m"} = \&{"threads::$m"};
322 }
323 XSLoader::load 'threads::shared';
324 for my $m (qw(cond_signal cond_broadcast cond_wait unlock share)) {
4038bebf 325 no strict 'refs';
43d3ddbe
JH
326 *{"Thread::$m"} = \&{"threads::shared::${m}_enabled"};
327 }
d7ceb7fc
JH
328 # trying to unimplement eval gives redefined warning
329 unimplement(qw(list done flags));
43d3ddbe
JH
330 } elsif ($othreads) {
331 XSLoader::load 'Thread';
332 unimplement(qw(unlock));
333 } else {
334 require Carp;
335 Carp::croak("This Perl has neither ithreads not 5005threads");
336 }
337}
338
3391;