1 package threads::shared;
8 use Scalar::Util qw(reftype refaddr blessed);
10 our $VERSION = '1.26';
11 my $XS_VERSION = $VERSION;
12 $VERSION = eval $VERSION;
14 # Declare that we have been loaded
15 $threads::shared::threads_shared = 1;
17 # Load the XS code, if applicable
18 if ($threads::threads) {
20 XSLoader::load('threads::shared', $XS_VERSION);
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.
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 }
44 # Exported subroutines
45 my @EXPORT = qw(share is_shared cond_wait cond_timedwait
46 cond_signal cond_broadcast shared_clone);
47 if ($threads::threads) {
48 push(@EXPORT, 'bless');
51 # Export subroutine names
52 my $caller = caller();
53 foreach my $sym (@EXPORT) {
55 *{$caller.'::'.$sym} = \&{$sym};
60 # Predeclarations for internal functions
66 sub threads::shared::tie::SPLICE
69 Carp::croak('Splice not implemented for shared arrays');
73 # Create a thread-shared clone of a complex data structure or object
78 Carp::croak('Usage: shared_clone(REF)');
81 return $make_shared->(shift, {});
85 ### Internal Functions ###
87 # Used by shared_clone() to recursively clone
88 # a complex data structure or object
90 my ($item, $cloned) = @_;
92 # Just return the item if:
94 # 2. Already shared; or
95 # 3. Not running 'threads'.
96 return $item if (! ref($item) || is_shared($item) || ! $threads::threads);
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};
106 # Make copies of array, hash and scalar refs and refs of refs
108 my $ref_type = reftype($item);
111 if ($ref_type eq 'ARRAY') {
112 # Make empty shared array ref
114 # Add to clone checking hash
115 $cloned->{$addr} = $copy;
116 # Recursively copy and add contents
117 push(@$copy, map { $make_shared->($_, $cloned) } @$item);
121 elsif ($ref_type eq 'HASH') {
122 # Make empty shared hash ref
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);
133 elsif ($ref_type eq 'SCALAR') {
134 $copy = \do{ my $scalar = $$item; };
136 # Add to clone checking hash
137 $cloned->{$addr} = $copy;
140 # Copy of a ref of a ref
141 elsif ($ref_type eq 'REF') {
142 # Special handling for $x = \$x
143 if ($addr == refaddr($$item)) {
146 $cloned->{$addr} = $copy;
151 # Add to clone checking hash
152 $cloned->{$addr} = $copy;
153 # Recursively copy and add contents
154 $tmp = $make_shared->($$item, $cloned);
159 Carp::croak("Unsupported ref type: ", $ref_type);
162 # If input item is an object, then bless the copy into the same class
163 if (my $class = blessed($item)) {
164 bless($copy, $class);
167 # Clone READONLY flag
168 if ($ref_type eq 'SCALAR') {
169 if (Internals::SvREADONLY($$item)) {
170 Internals::SvREADONLY($$copy, 1) if ($] >= 5.008003);
173 if (Internals::SvREADONLY($item)) {
174 Internals::SvREADONLY($copy, 1) if ($] >= 5.008003);
186 threads::shared - Perl extension for sharing data structures between threads
190 This document describes threads::shared version 1.26
201 my ($scalar, @array, %hash);
206 $var = $scalar_value;
207 $var = $shared_ref_value;
208 $var = shared_clone($non_shared_ref_value);
209 $var = shared_clone({'foo' => [qw/foo bar baz/]});
211 $hsh{'foo'} = $scalar_value;
212 $hsh{'bar'} = $shared_ref_value;
213 $hsh{'baz'} = shared_clone($non_shared_ref_value);
214 $hsh{'quz'} = shared_clone([1..3]);
216 $ary[0] = $scalar_value;
217 $ary[1] = $shared_ref_value;
218 $ary[2] = shared_clone($non_shared_ref_value);
219 $ary[3] = shared_clone([ {}, [] ]);
224 cond_timedwait($scalar, time() + 30);
225 cond_broadcast(@array);
229 # condition var != lock var
230 cond_wait($var, $lockvar);
231 cond_timedwait($var, time()+30, $lockvar);
235 By default, variables are private to each thread, and each newly created
236 thread gets a private copy of each existing variable. This module allows you
237 to share variables across different threads (and pseudo-forks on Win32). It
238 is used together with the L<threads> module.
240 This module supports the sharing of the following data types only: scalars
241 and scalar refs, arrays and array refs, and hashes and hash refs.
245 The following functions are exported by this module: C<share>,
246 C<shared_clone>, C<is_shared>, C<cond_wait>, C<cond_timedwait>, C<cond_signal>
247 and C<cond_broadcast>
249 Note that if this module is imported when L<threads> has not yet been loaded,
250 then these functions all become no-ops. This makes it possible to write
251 modules that will work in both threaded and non-threaded environments.
259 C<share> takes a variable and marks it as shared:
261 my ($scalar, @array, %hash);
266 C<share> will return the shared rvalue, but always as a reference.
268 Variables can also be marked as shared at compile time by using the
269 C<:shared> attribute:
271 my ($var, %hash, @array) :shared;
273 Shared variables can only store scalars, refs of shared variables, or
274 refs of shared data (discussed in next section):
276 my ($var, %hash, @array) :shared;
281 $hash{'foo'} = 'bar';
284 # Storing shared refs
286 $hash{'ary'} = \@array;
289 # The following are errors:
290 # $var = \$bork; # ref of non-shared variable
291 # $hash{'bork'} = []; # non-shared array ref
292 # push(@array, { 'x' => 1 }); # non-shared hash ref
294 =item shared_clone REF
296 C<shared_clone> takes a reference, and returns a shared version of its
297 argument, preforming a deep copy on any non-shared elements. Any shared
298 elements in the argument are used as is (i.e., they are not cloned).
300 my $cpy = shared_clone({'foo' => [qw/foo bar baz/]});
302 Object status (i.e., the class an object is blessed into) is also cloned.
304 my $obj = {'foo' => [qw/foo bar baz/]};
306 my $cpy = shared_clone($obj);
307 print(ref($cpy), "\n"); # Outputs 'Foo'
309 For cloning empty array or hash refs, the following may also be used:
311 $var = &share([]); # Same as $var = share_clone([]);
312 $var = &share({}); # Same as $var = share_clone({});
314 =item is_shared VARIABLE
316 C<is_shared> checks if the specified variable is shared or not. If shared,
317 returns the variable's internal ID (similar to
318 L<refaddr()|Scalar::Util/"refaddr EXPR">). Otherwise, returns C<undef>.
320 if (is_shared($var)) {
321 print("\$var is shared\n");
323 print("\$var is not shared\n");
328 C<lock> places a lock on a variable until the lock goes out of scope. If the
329 variable is locked by another thread, the C<lock> call will block until it's
330 available. Multiple calls to C<lock> by the same thread from within
331 dynamically nested scopes are safe -- the variable will remain locked until
332 the outermost lock on the variable goes out of scope.
334 Locking a container object, such as a hash or array, doesn't lock the elements
335 of that container. For example, if a thread does a C<lock(@a)>, any other
336 thread doing a C<lock($a[12])> won't block.
338 C<lock()> follows references exactly I<one> level. C<lock(\$a)> is equivalent
339 to C<lock($a)>, while C<lock(\\$a)> is not.
341 Note that you cannot explicitly unlock a variable; you can only wait for the
342 lock to go out of scope. This is most easily accomplished by locking the
343 variable inside a block.
348 # $var is locked from here to the end of the block
351 # $var is now unlocked
353 If you need more fine-grained control over shared variable access, see
354 L<Thread::Semaphore>.
356 =item cond_wait VARIABLE
358 =item cond_wait CONDVAR, LOCKVAR
360 The C<cond_wait> function takes a B<locked> variable as a parameter, unlocks
361 the variable, and blocks until another thread does a C<cond_signal> or
362 C<cond_broadcast> for that same locked variable. The variable that
363 C<cond_wait> blocked on is relocked after the C<cond_wait> is satisfied. If
364 there are multiple threads C<cond_wait>ing on the same variable, all but one
365 will re-block waiting to reacquire the lock on the variable. (So if you're only
366 using C<cond_wait> for synchronisation, give up the lock as soon as possible).
367 The two actions of unlocking the variable and entering the blocked wait state
368 are atomic, the two actions of exiting from the blocked wait state and
369 re-locking the variable are not.
371 In its second form, C<cond_wait> takes a shared, B<unlocked> variable followed
372 by a shared, B<locked> variable. The second variable is unlocked and thread
373 execution suspended until another thread signals the first variable.
375 It is important to note that the variable can be notified even if no thread
376 C<cond_signal> or C<cond_broadcast> on the variable. It is therefore
377 important to check the value of the variable and go back to waiting if the
378 requirement is not fulfilled. For example, to pause until a shared counter
381 { lock($counter); cond_wait($count) until $counter == 0; }
383 =item cond_timedwait VARIABLE, ABS_TIMEOUT
385 =item cond_timedwait CONDVAR, ABS_TIMEOUT, LOCKVAR
387 In its two-argument form, C<cond_timedwait> takes a B<locked> variable and an
388 absolute timeout as parameters, unlocks the variable, and blocks until the
389 timeout is reached or another thread signals the variable. A false value is
390 returned if the timeout is reached, and a true value otherwise. In either
391 case, the variable is re-locked upon return.
393 Like C<cond_wait>, this function may take a shared, B<locked> variable as an
394 additional parameter; in this case the first parameter is an B<unlocked>
395 condition variable protected by a distinct lock variable.
397 Again like C<cond_wait>, waking up and reacquiring the lock are not atomic,
398 and you should always check your desired condition after this function
399 returns. Since the timeout is an absolute value, however, it does not have to
400 be recalculated with each pass:
403 my $abs = time() + 15;
404 until ($ok = desired_condition($var)) {
405 last if !cond_timedwait($var, $abs);
407 # we got it if $ok, otherwise we timed out!
409 =item cond_signal VARIABLE
411 The C<cond_signal> function takes a B<locked> variable as a parameter and
412 unblocks one thread that's C<cond_wait>ing on that variable. If more than one
413 thread is blocked in a C<cond_wait> on that variable, only one (and which one
414 is indeterminate) will be unblocked.
416 If there are no threads blocked in a C<cond_wait> on the variable, the signal
417 is discarded. By always locking before signaling, you can (with care), avoid
418 signaling before another thread has entered cond_wait().
420 C<cond_signal> will normally generate a warning if you attempt to use it on an
421 unlocked variable. On the rare occasions where doing this may be sensible, you
422 can suppress the warning with:
424 { no warnings 'threads'; cond_signal($foo); }
426 =item cond_broadcast VARIABLE
428 The C<cond_broadcast> function works similarly to C<cond_signal>.
429 C<cond_broadcast>, though, will unblock B<all> the threads that are blocked in
430 a C<cond_wait> on the locked variable, rather than only one.
436 L<threads::shared> exports a version of L<bless()|perlfunc/"bless REF"> that
437 works on shared objects such that I<blessings> propagate across threads.
439 # Create a shared 'Foo' object
440 my $foo :shared = shared_clone({});
443 # Create a shared 'Bar' object
444 my $bar :shared = shared_clone({});
447 # Put 'bar' inside 'foo'
448 $foo->{'bar'} = $bar;
450 # Rebless the objects via a thread
451 threads->create(sub {
452 # Rebless the outer object
455 # Cannot directly rebless the inner object
456 #bless($foo->{'bar'}, 'Yang');
458 # Retrieve and rebless the inner object
459 my $obj = $foo->{'bar'};
461 $foo->{'bar'} = $obj;
465 print(ref($foo), "\n"); # Prints 'Yin'
466 print(ref($foo->{'bar'}), "\n"); # Prints 'Yang'
467 print(ref($bar), "\n"); # Also prints 'Yang'
471 L<threads::shared> is designed to disable itself silently if threads are not
472 available. This allows you to write modules and packages that can be used
473 in both threaded and non-threaded applications.
475 If you want access to threads, you must C<use threads> before you
476 C<use threads::shared>. L<threads> will emit a warning if you use it after
479 =head1 BUGS AND LIMITATIONS
481 When C<share> is used on arrays, hashes, array refs or hash refs, any data
482 they contain will be lost.
484 my @arr = qw(foo bar baz);
486 # @arr is now empty (i.e., == ());
488 # Create a 'foo' object
489 my $foo = { 'data' => 99 };
493 share($foo); # Contents are now wiped out
494 print("ERROR: \$foo is empty\n")
495 if (! exists($foo->{'data'}));
497 Therefore, populate such variables B<after> declaring them as shared. (Scalar
498 and scalar refs are not affected by this problem.)
500 It is often not wise to share an object unless the class itself has been
501 written to support sharing. For example, an object's destructor may get
502 called multiple times, once for each thread's scope exit. Another danger is
503 that the contents of hash-based objects will be lost due to the above
504 mentioned limitation. See F<examples/class.pl> (in the CPAN distribution of
505 this module) for how to create a class that supports object sharing.
507 Does not support C<splice> on arrays!
509 Taking references to the elements of shared arrays and hashes does not
510 autovivify the elements, and neither does slicing a shared array/hash over
511 non-existent indices/keys autovivify the elements.
513 C<share()> allows you to C<< share($hashref->{key}) >> without giving any
514 error message. But the C<< $hashref->{key} >> is B<not> shared, causing the
515 error "locking can only be used on shared values" to occur when you attempt to
516 C<< lock($hasref->{key}) >>.
518 Using L<refaddr()|Scalar::Util/"refaddr EXPR">) is unreliable for testing
519 whether or not two shared references are equivalent (e.g., when testing for
520 circular references). Use L<is_shared()/"is_shared VARIABLE">, instead:
524 use Scalar::Util qw(refaddr);
526 # If ref is shared, use threads::shared's internal ID.
527 # Otherwise, use refaddr().
528 my $addr1 = is_shared($ref1) || refaddr($ref1);
529 my $addr2 = is_shared($ref2) || refaddr($ref2);
531 if ($addr1 == $addr2) {
532 # The refs are equivalent
535 View existing bug reports at, and submit any new bugs, problems, patches, etc.
536 to: L<http://rt.cpan.org/Public/Dist/Display.html?Name=threads-shared>
540 L<threads::shared> Discussion Forum on CPAN:
541 L<http://www.cpanforum.com/dist/threads-shared>
543 Annotated POD for L<threads::shared>:
544 L<http://annocpan.org/~JDHEDDEN/threads-shared-1.26/shared.pm>
547 L<http://code.google.com/p/threads-shared/>
549 L<threads>, L<perlthrtut>
551 L<http://www.perl.com/pub/a/2002/06/11/threads.html> and
552 L<http://www.perl.com/pub/a/2002/09/04/threads.html>
554 Perl threads mailing list:
555 L<http://lists.cpan.org/showlist.cgi?name=iThreads>
559 Artur Bergman E<lt>sky AT crucially DOT netE<gt>
561 Documentation borrowed from the old Thread.pm.
563 CPAN version produced by Jerry D. Hedden E<lt>jdhedden AT cpan DOT orgE<gt>.
567 threads::shared is released under the same license as Perl.