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