threads::shared 1.22
[p5sagit/p5-mst-13.2.git] / ext / threads / shared / shared.pm
CommitLineData
b050c948 1package threads::shared;
73e09c8f 2
c46325ea 3use 5.008;
7473853a 4
b050c948 5use strict;
6use warnings;
73e09c8f 7
373098c0 8use Scalar::Util qw(reftype refaddr blessed);
9
6c791b15 10our $VERSION = '1.22';
7473853a 11my $XS_VERSION = $VERSION;
12$VERSION = eval $VERSION;
13
14# Declare that we have been loaded
15$threads::shared::threads_shared = 1;
16
17# Load the XS code, if applicable
18if ($threads::threads) {
19 require XSLoader;
20 XSLoader::load('threads::shared', $XS_VERSION);
21
22 *is_shared = \&_id;
23
24} else {
25 # String eval is generally evil, but we don't want these subs to
26 # exist at all if 'threads' is not loaded successfully.
27 # Vivifying them conditionally this way saves on average about 4K
28 # of memory per thread.
29 eval <<'_MARKER_';
30 sub share (\[$@%]) { return $_[0] }
31 sub is_shared (\[$@%]) { undef }
32 sub cond_wait (\[$@%];\[$@%]) { undef }
33 sub cond_timedwait (\[$@%]$;\[$@%]) { undef }
34 sub cond_signal (\[$@%]) { undef }
35 sub cond_broadcast (\[$@%]) { undef }
36_MARKER_
37}
38
39
40### Export ###
41
42sub import
43{
44 # Exported subroutines
45 my @EXPORT = qw(share is_shared cond_wait cond_timedwait
373098c0 46 cond_signal cond_broadcast shared_clone);
5c360ac5 47 if ($threads::threads) {
7473853a 48 push(@EXPORT, 'bless');
5c360ac5 49 }
7473853a 50
51 # Export subroutine names
52 my $caller = caller();
53 foreach my $sym (@EXPORT) {
54 no strict 'refs';
55 *{$caller.'::'.$sym} = \&{$sym};
df5c998e 56 }
57}
b050c948 58
7473853a 59
373098c0 60# Predeclarations for internal functions
61my ($make_shared);
62
63
7473853a 64### Methods, etc. ###
dab065ea 65
6b85e4fe 66sub threads::shared::tie::SPLICE
67{
7473853a 68 require Carp;
69 Carp::croak('Splice not implemented for shared arrays');
6b85e4fe 70}
71
373098c0 72
73# Create a thread-shared clone of a complex data structure or object
74sub shared_clone
75{
76 if (@_ != 1) {
77 require Carp;
78 Carp::croak('Usage: shared_clone(REF)');
79 }
80
81 return $make_shared->(shift, {});
82}
83
84
85### Internal Functions ###
86
87# Used by shared_clone() to recursively clone
88# a complex data structure or object
89$make_shared = sub {
90 my ($item, $cloned) = @_;
91
92 # Just return the item if:
93 # 1. Not a ref;
94 # 2. Already shared; or
95 # 3. Not running 'threads'.
96 return $item if (! ref($item) || is_shared($item) || ! $threads::threads);
97
98 # Check for previously cloned references
99 # (this takes care of circular refs as well)
100 my $addr = refaddr($item);
101 if (exists($cloned->{$addr})) {
102 # Return the already existing clone
103 return $cloned->{$addr};
104 }
105
106 # Make copies of array, hash and scalar refs and refs of refs
107 my $copy;
108 my $ref_type = reftype($item);
109
110 # Copy an array ref
111 if ($ref_type eq 'ARRAY') {
112 # Make empty shared array ref
113 $copy = &share([]);
114 # Add to clone checking hash
115 $cloned->{$addr} = $copy;
116 # Recursively copy and add contents
117 push(@$copy, map { $make_shared->($_, $cloned) } @$item);
118 }
119
120 # Copy a hash ref
121 elsif ($ref_type eq 'HASH') {
122 # Make empty shared hash ref
123 $copy = &share({});
124 # Add to clone checking hash
125 $cloned->{$addr} = $copy;
126 # Recursively copy and add contents
127 foreach my $key (keys(%{$item})) {
128 $copy->{$key} = $make_shared->($item->{$key}, $cloned);
129 }
130 }
131
132 # Copy a scalar ref
133 elsif ($ref_type eq 'SCALAR') {
134 $copy = \do{ my $scalar = $$item; };
135 share($copy);
136 # Clone READONLY flag
137 if (Internals::SvREADONLY($$item)) {
138 Internals::SvREADONLY($$copy, 1);
139 }
140 # Add to clone checking hash
141 $cloned->{$addr} = $copy;
142 }
143
144 # Copy of a ref of a ref
145 elsif ($ref_type eq 'REF') {
146 # Special handling for $x = \$x
147 if ($addr == refaddr($$item)) {
148 $copy = \$copy;
149 share($copy);
150 $cloned->{$addr} = $copy;
151 } else {
152 my $tmp;
153 $copy = \$tmp;
154 share($copy);
155 # Add to clone checking hash
156 $cloned->{$addr} = $copy;
157 # Recursively copy and add contents
158 $tmp = $make_shared->($$item, $cloned);
159 }
160
161 } else {
162 require Carp;
163 Carp::croak("Unsupported ref type: ", $ref_type);
164 }
165
166 # If input item is an object, then bless the copy into the same class
167 if (my $class = blessed($item)) {
168 bless($copy, $class);
169 }
170
171 # Clone READONLY flag
172 if (Internals::SvREADONLY($item)) {
173 Internals::SvREADONLY($copy, 1);
174 }
175
176 return $copy;
177};
178
7473853a 1791;
180
b050c948 181__END__
182
183=head1 NAME
184
185threads::shared - Perl extension for sharing data structures between threads
186
7473853a 187=head1 VERSION
188
6c791b15 189This document describes threads::shared version 1.22
7473853a 190
b050c948 191=head1 SYNOPSIS
192
73e09c8f 193 use threads;
b050c948 194 use threads::shared;
195
7473853a 196 my $var :shared;
373098c0 197 my %hsh :shared;
198 my @ary :shared;
38875929 199
3b29be8d 200 my ($scalar, @array, %hash);
4cab98c0 201 share($scalar);
202 share(@array);
aaf3876d 203 share(%hash);
373098c0 204
205 $var = $scalar_value;
206 $var = $shared_ref_value;
207 $var = shared_clone($non_shared_ref_value);
208 $var = shared_clone({'foo' => [qw/foo bar baz/]});
209
210 $hsh{'foo'} = $scalar_value;
211 $hsh{'bar'} = $shared_ref_value;
212 $hsh{'baz'} = shared_clone($non_shared_ref_value);
213 $hsh{'quz'} = shared_clone([1..3]);
214
215 $ary[0] = $scalar_value;
216 $ary[1] = $shared_ref_value;
217 $ary[2] = shared_clone($non_shared_ref_value);
218 $ary[3] = shared_clone([ {}, [] ]);
b050c948 219
38875929 220 { lock(%hash); ... }
221
b050c948 222 cond_wait($scalar);
a0e036c1 223 cond_timedwait($scalar, time() + 30);
515f0976 224 cond_broadcast(@array);
225 cond_signal(%hash);
b050c948 226
7473853a 227 my $lockvar :shared;
a0e036c1 228 # condition var != lock var
229 cond_wait($var, $lockvar);
230 cond_timedwait($var, time()+30, $lockvar);
231
b050c948 232=head1 DESCRIPTION
233
38875929 234By default, variables are private to each thread, and each newly created
7473853a 235thread gets a private copy of each existing variable. This module allows you
373098c0 236to share variables across different threads (and pseudo-forks on Win32). It
237is used together with the L<threads> module.
238
239This module supports the sharing of the following data types only: scalars
240and scalar refs, arrays and array refs, and hashes and hash refs.
b050c948 241
515f0976 242=head1 EXPORT
b050c948 243
373098c0 244The following functions are exported by this module: C<share>,
245C<shared_clone>, C<is_shared>, C<cond_wait>, C<cond_timedwait>, C<cond_signal>
246and C<cond_broadcast>
515f0976 247
7473853a 248Note that if this module is imported when L<threads> has not yet been loaded,
249then these functions all become no-ops. This makes it possible to write
250modules that will work in both threaded and non-threaded environments.
e67b86b3 251
515f0976 252=head1 FUNCTIONS
253
254=over 4
255
256=item share VARIABLE
257
373098c0 258C<share> takes a variable and marks it as shared:
259
260 my ($scalar, @array, %hash);
261 share($scalar);
262 share(@array);
263 share(%hash);
264
265C<share> will return the shared rvalue, but always as a reference.
515f0976 266
373098c0 267Variables can also be marked as shared at compile time by using the
268C<:shared> attribute:
38875929 269
373098c0 270 my ($var, %hash, @array) :shared;
caf25f3b 271
373098c0 272Shared variables can only store scalars, refs of shared variables, or
273refs of shared data (discussed in next section):
7473853a 274
373098c0 275 my ($var, %hash, @array) :shared;
276 my $bork;
277
278 # Storing scalars
279 $var = 1;
280 $hash{'foo'} = 'bar';
281 $array[0] = 1.5;
282
283 # Storing shared refs
284 $var = \%hash;
285 $hash{'ary'} = \@array;
286 $array[1] = \$var;
287
288 # The following are errors:
289 # $var = \$bork; # ref of non-shared variable
290 # $hash{'bork'} = []; # non-shared array ref
291 # push(@array, { 'x' => 1 }); # non-shared hash ref
7473853a 292
373098c0 293=item shared_clone REF
ca5ff8b2 294
373098c0 295C<shared_clone> takes a reference, and returns a shared version of its
296argument, preforming a deep copy on any non-shared elements. Any shared
297elements in the argument are used as is (i.e., they are not cloned).
298
299 my $cpy = shared_clone({'foo' => [qw/foo bar baz/]});
300
301Object status (i.e., the class an object is blessed into) is also cloned.
302
303 my $obj = {'foo' => [qw/foo bar baz/]};
304 bless($obj, 'Foo');
305 my $cpy = shared_clone($obj);
306 print(ref($cpy), "\n"); # Outputs 'Foo'
307
308For cloning empty array or hash refs, the following may also be used:
309
310 $var = &share([]); # Same as $var = share_clone([]);
311 $var = &share({}); # Same as $var = share_clone({});
ca5ff8b2 312
7473853a 313=item is_shared VARIABLE
314
315C<is_shared> checks if the specified variable is shared or not. If shared,
316returns the variable's internal ID (similar to
317L<refaddr()|Scalar::Util/"refaddr EXPR">). Otherwise, returns C<undef>.
318
319 if (is_shared($var)) {
320 print("\$var is shared\n");
321 } else {
322 print("\$var is not shared\n");
323 }
ca5ff8b2 324
515f0976 325=item lock VARIABLE
326
7473853a 327C<lock> places a lock on a variable until the lock goes out of scope. If the
328variable is locked by another thread, the C<lock> call will block until it's
2b936299 329available. Multiple calls to C<lock> by the same thread from within
330dynamically nested scopes are safe -- the variable will remain locked until
331the outermost lock on the variable goes out of scope.
7473853a 332
2b936299 333Locking a container object, such as a hash or array, doesn't lock the elements
334of that container. For example, if a thread does a C<lock(@a)>, any other
335thread doing a C<lock($a[12])> won't block.
515f0976 336
2b936299 337C<lock()> follows references exactly I<one> level. C<lock(\$a)> is equivalent
338to C<lock($a)>, while C<lock(\\$a)> is not.
515f0976 339
7473853a 340Note that you cannot explicitly unlock a variable; you can only wait for the
341lock to go out of scope. This is most easily accomplished by locking the
342variable inside a block.
515f0976 343
7473853a 344 my $var :shared;
345 {
346 lock($var);
347 # $var is locked from here to the end of the block
348 ...
349 }
350 # $var is now unlocked
351
352If you need more fine-grained control over shared variable access, see
353L<Thread::Semaphore>.
515f0976 354
355=item cond_wait VARIABLE
356
a0e036c1 357=item cond_wait CONDVAR, LOCKVAR
358
7473853a 359The C<cond_wait> function takes a B<locked> variable as a parameter, unlocks
360the variable, and blocks until another thread does a C<cond_signal> or
361C<cond_broadcast> for that same locked variable. The variable that
362C<cond_wait> blocked on is relocked after the C<cond_wait> is satisfied. If
363there are multiple threads C<cond_wait>ing on the same variable, all but one
7c8caac0 364will re-block waiting to reacquire the lock on the variable. (So if you're only
7473853a 365using C<cond_wait> for synchronisation, give up the lock as soon as possible).
366The two actions of unlocking the variable and entering the blocked wait state
367are atomic, the two actions of exiting from the blocked wait state and
7c8caac0 368re-locking the variable are not.
7473853a 369
370In its second form, C<cond_wait> takes a shared, B<unlocked> variable followed
371by a shared, B<locked> variable. The second variable is unlocked and thread
372execution suspended until another thread signals the first variable.
373
374It is important to note that the variable can be notified even if no thread
375C<cond_signal> or C<cond_broadcast> on the variable. It is therefore
376important to check the value of the variable and go back to waiting if the
377requirement is not fulfilled. For example, to pause until a shared counter
378drops to zero:
379
380 { lock($counter); cond_wait($count) until $counter == 0; }
a0e036c1 381
382=item cond_timedwait VARIABLE, ABS_TIMEOUT
383
384=item cond_timedwait CONDVAR, ABS_TIMEOUT, LOCKVAR
385
7473853a 386In its two-argument form, C<cond_timedwait> takes a B<locked> variable and an
387absolute timeout as parameters, unlocks the variable, and blocks until the
388timeout is reached or another thread signals the variable. A false value is
389returned if the timeout is reached, and a true value otherwise. In either
390case, the variable is re-locked upon return.
a0e036c1 391
7473853a 392Like C<cond_wait>, this function may take a shared, B<locked> variable as an
393additional parameter; in this case the first parameter is an B<unlocked>
394condition variable protected by a distinct lock variable.
a0e036c1 395
7473853a 396Again like C<cond_wait>, waking up and reacquiring the lock are not atomic,
397and you should always check your desired condition after this function
398returns. Since the timeout is an absolute value, however, it does not have to
399be recalculated with each pass:
a0e036c1 400
7473853a 401 lock($var);
402 my $abs = time() + 15;
403 until ($ok = desired_condition($var)) {
a0e036c1 404 last if !cond_timedwait($var, $abs);
7473853a 405 }
406 # we got it if $ok, otherwise we timed out!
515f0976 407
408=item cond_signal VARIABLE
409
7473853a 410The C<cond_signal> function takes a B<locked> variable as a parameter and
411unblocks one thread that's C<cond_wait>ing on that variable. If more than one
412thread is blocked in a C<cond_wait> on that variable, only one (and which one
413is indeterminate) will be unblocked.
515f0976 414
7473853a 415If there are no threads blocked in a C<cond_wait> on the variable, the signal
416is discarded. By always locking before signaling, you can (with care), avoid
417signaling before another thread has entered cond_wait().
38875929 418
7473853a 419C<cond_signal> will normally generate a warning if you attempt to use it on an
420unlocked variable. On the rare occasions where doing this may be sensible, you
ba2940ce 421can suppress the warning with:
38875929 422
7473853a 423 { no warnings 'threads'; cond_signal($foo); }
515f0976 424
425=item cond_broadcast VARIABLE
426
427The C<cond_broadcast> function works similarly to C<cond_signal>.
7473853a 428C<cond_broadcast>, though, will unblock B<all> the threads that are blocked in
429a C<cond_wait> on the locked variable, rather than only one.
b050c948 430
4cab98c0 431=back
dab065ea 432
7473853a 433=head1 OBJECTS
434
435L<threads::shared> exports a version of L<bless()|perlfunc/"bless REF"> that
2b936299 436works on shared objects such that I<blessings> propagate across threads.
7473853a 437
373098c0 438 # Create a shared 'Foo' object
439 my $foo :shared = shared_clone({});
440 bless($foo, 'Foo');
7473853a 441
373098c0 442 # Create a shared 'Bar' object
443 my $bar :shared = shared_clone({});
444 bless($bar, 'Bar');
7473853a 445
446 # Put 'bar' inside 'foo'
447 $foo->{'bar'} = $bar;
448
449 # Rebless the objects via a thread
450 threads->create(sub {
451 # Rebless the outer object
373098c0 452 bless($foo, 'Yin');
7473853a 453
454 # Cannot directly rebless the inner object
373098c0 455 #bless($foo->{'bar'}, 'Yang');
7473853a 456
457 # Retrieve and rebless the inner object
458 my $obj = $foo->{'bar'};
373098c0 459 bless($obj, 'Yang');
7473853a 460 $foo->{'bar'} = $obj;
461
462 })->join();
463
373098c0 464 print(ref($foo), "\n"); # Prints 'Yin'
465 print(ref($foo->{'bar'}), "\n"); # Prints 'Yang'
466 print(ref($bar), "\n"); # Also prints 'Yang'
7473853a 467
dab065ea 468=head1 NOTES
469
33d16ee7 470L<threads::shared> is designed to disable itself silently if threads are not
471available. This allows you to write modules and packages that can be used
472in both threaded and non-threaded applications.
473
474If you want access to threads, you must C<use threads> before you
7473853a 475C<use threads::shared>. L<threads> will emit a warning if you use it after
476L<threads::shared>.
dab065ea 477
7473853a 478=head1 BUGS AND LIMITATIONS
b050c948 479
7473853a 480When C<share> is used on arrays, hashes, array refs or hash refs, any data
481they contain will be lost.
515f0976 482
7473853a 483 my @arr = qw(foo bar baz);
484 share(@arr);
485 # @arr is now empty (i.e., == ());
b050c948 486
7473853a 487 # Create a 'foo' object
488 my $foo = { 'data' => 99 };
489 bless($foo, 'foo');
58122748 490
7473853a 491 # Share the object
492 share($foo); # Contents are now wiped out
493 print("ERROR: \$foo is empty\n")
494 if (! exists($foo->{'data'}));
3d32476b 495
7473853a 496Therefore, populate such variables B<after> declaring them as shared. (Scalar
497and scalar refs are not affected by this problem.)
498
499It is often not wise to share an object unless the class itself has been
2b936299 500written to support sharing. For example, an object's destructor may get
501called multiple times, once for each thread's scope exit. Another danger is
502that the contents of hash-based objects will be lost due to the above
503mentioned limitation. See F<examples/class.pl> (in the CPAN distribution of
504this module) for how to create a class that supports object sharing.
b050c948 505
7473853a 506Does not support C<splice> on arrays!
b050c948 507
7473853a 508Taking references to the elements of shared arrays and hashes does not
509autovivify the elements, and neither does slicing a shared array/hash over
510non-existent indices/keys autovivify the elements.
511
512C<share()> allows you to C<< share($hashref->{key}) >> without giving any
513error message. But the C<< $hashref->{key} >> is B<not> shared, causing the
514error "locking can only be used on shared values" to occur when you attempt to
515C<< lock($hasref->{key}) >>.
b050c948 516
f6d55995 517Using L<refaddr()|Scalar::Util/"refaddr EXPR">) is unreliable for testing
518whether or not two shared references are equivalent (e.g., when testing for
519circular references). Use L<is_shared()/"is_shared VARIABLE">, instead:
520
521 use threads;
522 use threads::shared;
523 use Scalar::Util qw(refaddr);
524
525 # If ref is shared, use threads::shared's internal ID.
526 # Otherwise, use refaddr().
527 my $addr1 = is_shared($ref1) || refaddr($ref1);
528 my $addr2 = is_shared($ref2) || refaddr($ref2);
529
530 if ($addr1 == $addr2) {
531 # The refs are equivalent
532 }
533
7473853a 534View existing bug reports at, and submit any new bugs, problems, patches, etc.
794f4697 535to: L<http://rt.cpan.org/Public/Dist/Display.html?Name=threads-shared>
515f0976 536
b050c948 537=head1 SEE ALSO
538
7473853a 539L<threads::shared> Discussion Forum on CPAN:
540L<http://www.cpanforum.com/dist/threads-shared>
541
542Annotated POD for L<threads::shared>:
6c791b15 543L<http://annocpan.org/~JDHEDDEN/threads-shared-1.22/shared.pm>
05b59262 544
545Source repository:
546L<http://code.google.com/p/threads-shared/>
7473853a 547
548L<threads>, L<perlthrtut>
549
550L<http://www.perl.com/pub/a/2002/06/11/threads.html> and
551L<http://www.perl.com/pub/a/2002/09/04/threads.html>
552
553Perl threads mailing list:
554L<http://lists.cpan.org/showlist.cgi?name=iThreads>
555
556=head1 AUTHOR
557
558Artur Bergman E<lt>sky AT crucially DOT netE<gt>
559
7473853a 560Documentation borrowed from the old Thread.pm.
561
562CPAN version produced by Jerry D. Hedden E<lt>jdhedden AT cpan DOT orgE<gt>.
b050c948 563
6c791b15 564=head1 LICENSE
565
566threads::shared is released under the same license as Perl.
567
b050c948 568=cut