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