1package threads::shared; 2 3use 5.008; 4 5use strict; 6use warnings; 7use Config; 8 9use Scalar::Util qw(reftype refaddr blessed); 10 11our $VERSION = '1.60'; # Please update the pod, too. 12my $XS_VERSION = $VERSION; 13$VERSION = eval $VERSION; 14 15# Declare that we have been loaded 16$threads::shared::threads_shared = 1; 17 18# Method of complaint about things we can't clone 19$threads::shared::clone_warn = undef; 20 21# Load the XS code, if applicable 22if ($Config::Config{'useithreads'} && $threads::threads) { 23 require XSLoader; 24 XSLoader::load('threads::shared', $XS_VERSION); 25 26 *is_shared = \&_id; 27 28} else { 29 # String eval is generally evil, but we don't want these subs to 30 # exist at all if 'threads' is not loaded successfully. 31 # Vivifying them conditionally this way saves on average about 4K 32 # of memory per thread. 33 eval <<'_MARKER_'; 34 sub share (\[$@%]) { return $_[0] } 35 sub is_shared (\[$@%]) { undef } 36 sub cond_wait (\[$@%];\[$@%]) { undef } 37 sub cond_timedwait (\[$@%]$;\[$@%]) { undef } 38 sub cond_signal (\[$@%]) { undef } 39 sub cond_broadcast (\[$@%]) { undef } 40_MARKER_ 41} 42 43 44### Export ### 45 46sub import 47{ 48 # Exported subroutines 49 my @EXPORT = qw(share is_shared cond_wait cond_timedwait 50 cond_signal cond_broadcast shared_clone); 51 if ($threads::threads) { 52 push(@EXPORT, 'bless'); 53 } 54 55 # Export subroutine names 56 my $caller = caller(); 57 foreach my $sym (@EXPORT) { 58 no strict 'refs'; 59 *{$caller.'::'.$sym} = \&{$sym}; 60 } 61} 62 63 64# Predeclarations for internal functions 65my ($make_shared); 66 67 68### Methods, etc. ### 69 70sub threads::shared::tie::SPLICE 71{ 72 require Carp; 73 Carp::croak('Splice not implemented for shared arrays'); 74} 75 76 77# Create a thread-shared clone of a complex data structure or object 78sub shared_clone 79{ 80 if (@_ != 1) { 81 require Carp; 82 Carp::croak('Usage: shared_clone(REF)'); 83 } 84 85 return $make_shared->(shift, {}); 86} 87 88 89### Internal Functions ### 90 91# Used by shared_clone() to recursively clone 92# a complex data structure or object 93$make_shared = sub { 94 my ($item, $cloned) = @_; 95 96 # Just return the item if: 97 # 1. Not a ref; 98 # 2. Already shared; or 99 # 3. Not running 'threads'. 100 return $item if (! ref($item) || is_shared($item) || ! $threads::threads); 101 102 # Check for previously cloned references 103 # (this takes care of circular refs as well) 104 my $addr = refaddr($item); 105 if (exists($cloned->{$addr})) { 106 # Return the already existing clone 107 return $cloned->{$addr}; 108 } 109 110 # Make copies of array, hash and scalar refs and refs of refs 111 my $copy; 112 my $ref_type = reftype($item); 113 114 # Copy an array ref 115 if ($ref_type eq 'ARRAY') { 116 # Make empty shared array ref 117 $copy = &share([]); 118 # Add to clone checking hash 119 $cloned->{$addr} = $copy; 120 # Recursively copy and add contents 121 push(@$copy, map { $make_shared->($_, $cloned) } @$item); 122 } 123 124 # Copy a hash ref 125 elsif ($ref_type eq 'HASH') { 126 # Make empty shared hash ref 127 $copy = &share({}); 128 # Add to clone checking hash 129 $cloned->{$addr} = $copy; 130 # Recursively copy and add contents 131 foreach my $key (keys(%{$item})) { 132 $copy->{$key} = $make_shared->($item->{$key}, $cloned); 133 } 134 } 135 136 # Copy a scalar ref 137 elsif ($ref_type eq 'SCALAR') { 138 $copy = \do{ my $scalar = $$item; }; 139 share($copy); 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 if (! defined($threads::shared::clone_warn)) { 164 Carp::croak("Unsupported ref type: ", $ref_type); 165 } elsif ($threads::shared::clone_warn) { 166 Carp::carp("Unsupported ref type: ", $ref_type); 167 } 168 return undef; 169 } 170 171 # If input item is an object, then bless the copy into the same class 172 if (my $class = blessed($item)) { 173 bless($copy, $class); 174 } 175 176 # Clone READONLY flag 177 if ($ref_type eq 'SCALAR') { 178 if (Internals::SvREADONLY($$item)) { 179 Internals::SvREADONLY($$copy, 1) if ($] >= 5.008003); 180 } 181 } 182 if (Internals::SvREADONLY($item)) { 183 Internals::SvREADONLY($copy, 1) if ($] >= 5.008003); 184 } 185 186 return $copy; 187}; 188 1891; 190 191__END__ 192 193=head1 NAME 194 195threads::shared - Perl extension for sharing data structures between threads 196 197=head1 VERSION 198 199This document describes threads::shared version 1.60 200 201=head1 SYNOPSIS 202 203 use threads; 204 use threads::shared; 205 206 my $var :shared; 207 my %hsh :shared; 208 my @ary :shared; 209 210 my ($scalar, @array, %hash); 211 share($scalar); 212 share(@array); 213 share(%hash); 214 215 $var = $scalar_value; 216 $var = $shared_ref_value; 217 $var = shared_clone($non_shared_ref_value); 218 $var = shared_clone({'foo' => [qw/foo bar baz/]}); 219 220 $hsh{'foo'} = $scalar_value; 221 $hsh{'bar'} = $shared_ref_value; 222 $hsh{'baz'} = shared_clone($non_shared_ref_value); 223 $hsh{'quz'} = shared_clone([1..3]); 224 225 $ary[0] = $scalar_value; 226 $ary[1] = $shared_ref_value; 227 $ary[2] = shared_clone($non_shared_ref_value); 228 $ary[3] = shared_clone([ {}, [] ]); 229 230 { lock(%hash); ... } 231 232 cond_wait($scalar); 233 cond_timedwait($scalar, time() + 30); 234 cond_broadcast(@array); 235 cond_signal(%hash); 236 237 my $lockvar :shared; 238 # condition var != lock var 239 cond_wait($var, $lockvar); 240 cond_timedwait($var, time()+30, $lockvar); 241 242=head1 DESCRIPTION 243 244By default, variables are private to each thread, and each newly created 245thread gets a private copy of each existing variable. This module allows you 246to share variables across different threads (and pseudo-forks on Win32). It 247is used together with the L<threads> module. 248 249This module supports the sharing of the following data types only: scalars 250and scalar refs, arrays and array refs, and hashes and hash refs. 251 252=head1 EXPORT 253 254The following functions are exported by this module: C<share>, 255C<shared_clone>, C<is_shared>, C<cond_wait>, C<cond_timedwait>, C<cond_signal> 256and C<cond_broadcast> 257 258Note that if this module is imported when L<threads> has not yet been loaded, 259then these functions all become no-ops. This makes it possible to write 260modules that will work in both threaded and non-threaded environments. 261 262=head1 FUNCTIONS 263 264=over 4 265 266=item share VARIABLE 267 268C<share> takes a variable and marks it as shared: 269 270 my ($scalar, @array, %hash); 271 share($scalar); 272 share(@array); 273 share(%hash); 274 275C<share> will return the shared rvalue, but always as a reference. 276 277Variables can also be marked as shared at compile time by using the 278C<:shared> attribute: 279 280 my ($var, %hash, @array) :shared; 281 282Shared variables can only store scalars, refs of shared variables, or 283refs of shared data (discussed in next section): 284 285 my ($var, %hash, @array) :shared; 286 my $bork; 287 288 # Storing scalars 289 $var = 1; 290 $hash{'foo'} = 'bar'; 291 $array[0] = 1.5; 292 293 # Storing shared refs 294 $var = \%hash; 295 $hash{'ary'} = \@array; 296 $array[1] = \$var; 297 298 # The following are errors: 299 # $var = \$bork; # ref of non-shared variable 300 # $hash{'bork'} = []; # non-shared array ref 301 # push(@array, { 'x' => 1 }); # non-shared hash ref 302 303=item shared_clone REF 304 305C<shared_clone> takes a reference, and returns a shared version of its 306argument, performing a deep copy on any non-shared elements. Any shared 307elements in the argument are used as is (i.e., they are not cloned). 308 309 my $cpy = shared_clone({'foo' => [qw/foo bar baz/]}); 310 311Object status (i.e., the class an object is blessed into) is also cloned. 312 313 my $obj = {'foo' => [qw/foo bar baz/]}; 314 bless($obj, 'Foo'); 315 my $cpy = shared_clone($obj); 316 print(ref($cpy), "\n"); # Outputs 'Foo' 317 318For cloning empty array or hash refs, the following may also be used: 319 320 $var = &share([]); # Same as $var = shared_clone([]); 321 $var = &share({}); # Same as $var = shared_clone({}); 322 323Not all Perl data types can be cloned (e.g., globs, code refs). By default, 324C<shared_clone> will L<croak|Carp> if it encounters such items. To change 325this behaviour to a warning, then set the following: 326 327 $threads::shared::clone_warn = 1; 328 329In this case, C<undef> will be substituted for the item to be cloned. If 330set to zero: 331 332 $threads::shared::clone_warn = 0; 333 334then the C<undef> substitution will be performed silently. 335 336=item is_shared VARIABLE 337 338C<is_shared> checks if the specified variable is shared or not. If shared, 339returns the variable's internal ID (similar to 340C<refaddr()> (see L<Scalar::Util>). Otherwise, returns C<undef>. 341 342 if (is_shared($var)) { 343 print("\$var is shared\n"); 344 } else { 345 print("\$var is not shared\n"); 346 } 347 348When used on an element of an array or hash, C<is_shared> checks if the 349specified element belongs to a shared array or hash. (It does not check 350the contents of that element.) 351 352 my %hash :shared; 353 if (is_shared(%hash)) { 354 print("\%hash is shared\n"); 355 } 356 357 $hash{'elem'} = 1; 358 if (is_shared($hash{'elem'})) { 359 print("\$hash{'elem'} is in a shared hash\n"); 360 } 361 362=item lock VARIABLE 363 364C<lock> places a B<advisory> lock on a variable until the lock goes out of 365scope. If the variable is locked by another thread, the C<lock> call will 366block until it's available. Multiple calls to C<lock> by the same thread from 367within dynamically nested scopes are safe -- the variable will remain locked 368until the outermost lock on the variable goes out of scope. 369 370C<lock> follows references exactly I<one> level: 371 372 my %hash :shared; 373 my $ref = \%hash; 374 lock($ref); # This is equivalent to lock(%hash) 375 376Note that you cannot explicitly unlock a variable; you can only wait for the 377lock to go out of scope. This is most easily accomplished by locking the 378variable inside a block. 379 380 my $var :shared; 381 { 382 lock($var); 383 # $var is locked from here to the end of the block 384 ... 385 } 386 # $var is now unlocked 387 388As locks are advisory, they do not prevent data access or modification by 389another thread that does not itself attempt to obtain a lock on the variable. 390 391You cannot lock the individual elements of a container variable: 392 393 my %hash :shared; 394 $hash{'foo'} = 'bar'; 395 #lock($hash{'foo'}); # Error 396 lock(%hash); # Works 397 398If you need more fine-grained control over shared variable access, see 399L<Thread::Semaphore>. 400 401=item cond_wait VARIABLE 402 403=item cond_wait CONDVAR, LOCKVAR 404 405The C<cond_wait> function takes a B<locked> variable as a parameter, unlocks 406the variable, and blocks until another thread does a C<cond_signal> or 407C<cond_broadcast> for that same locked variable. The variable that 408C<cond_wait> blocked on is re-locked after the C<cond_wait> is satisfied. If 409there are multiple threads C<cond_wait>ing on the same variable, all but one 410will re-block waiting to reacquire the 411lock on the variable. (So if you're only 412using C<cond_wait> for synchronization, give up the lock as soon as possible). 413The two actions of unlocking the variable and entering the blocked wait state 414are atomic, the two actions of exiting from the blocked wait state and 415re-locking the variable are not. 416 417In its second form, C<cond_wait> takes a shared, B<unlocked> variable followed 418by a shared, B<locked> variable. The second variable is unlocked and thread 419execution suspended until another thread signals the first variable. 420 421It is important to note that the variable can be notified even if no thread 422C<cond_signal> or C<cond_broadcast> on the variable. It is therefore 423important to check the value of the variable and go back to waiting if the 424requirement is not fulfilled. For example, to pause until a shared counter 425drops to zero: 426 427 { lock($counter); cond_wait($counter) until $counter == 0; } 428 429=item cond_timedwait VARIABLE, ABS_TIMEOUT 430 431=item cond_timedwait CONDVAR, ABS_TIMEOUT, LOCKVAR 432 433In its two-argument form, C<cond_timedwait> takes a B<locked> variable and an 434absolute timeout in I<epoch> seconds (see L<time() in perlfunc|perlfunc/time> 435for more) as parameters, unlocks the variable, and blocks until the 436timeout is reached or another thread signals the variable. A false value is 437returned if the timeout is reached, and a true value otherwise. In either 438case, the variable is re-locked upon return. 439 440Like C<cond_wait>, this function may take a shared, B<locked> variable as an 441additional parameter; in this case the first parameter is an B<unlocked> 442condition variable protected by a distinct lock variable. 443 444Again like C<cond_wait>, waking up and reacquiring the lock are not atomic, 445and you should always check your desired condition after this function 446returns. Since the timeout is an absolute value, however, it does not have to 447be recalculated with each pass: 448 449 lock($var); 450 my $abs = time() + 15; 451 until ($ok = desired_condition($var)) { 452 last if !cond_timedwait($var, $abs); 453 } 454 # we got it if $ok, otherwise we timed out! 455 456=item cond_signal VARIABLE 457 458The C<cond_signal> function takes a B<locked> variable as a parameter and 459unblocks one thread that's C<cond_wait>ing 460on that variable. If more than one 461thread is blocked in a C<cond_wait> on that variable, only one (and which one 462is indeterminate) will be unblocked. 463 464If there are no threads blocked in a C<cond_wait> on the variable, the signal 465is discarded. By always locking before 466signaling, you can (with care), avoid 467signaling before another thread has entered cond_wait(). 468 469C<cond_signal> will normally generate a warning if you attempt to use it on an 470unlocked variable. On the rare occasions 471where doing this may be sensible, you 472can suppress the warning with: 473 474 { no warnings 'threads'; cond_signal($foo); } 475 476=item cond_broadcast VARIABLE 477 478The C<cond_broadcast> function works similarly to C<cond_signal>. 479C<cond_broadcast>, though, will unblock B<all> the threads that are blocked in 480a C<cond_wait> on the locked variable, rather than only one. 481 482=back 483 484=head1 OBJECTS 485 486L<threads::shared> exports a version of L<bless()|perlfunc/"bless REF"> that 487works on shared objects such that I<blessings> propagate across threads. 488 489 # Create a shared 'Foo' object 490 my $foo :shared = shared_clone({}); 491 bless($foo, 'Foo'); 492 493 # Create a shared 'Bar' object 494 my $bar :shared = shared_clone({}); 495 bless($bar, 'Bar'); 496 497 # Put 'bar' inside 'foo' 498 $foo->{'bar'} = $bar; 499 500 # Rebless the objects via a thread 501 threads->create(sub { 502 # Rebless the outer object 503 bless($foo, 'Yin'); 504 505 # Cannot directly rebless the inner object 506 #bless($foo->{'bar'}, 'Yang'); 507 508 # Retrieve and rebless the inner object 509 my $obj = $foo->{'bar'}; 510 bless($obj, 'Yang'); 511 $foo->{'bar'} = $obj; 512 513 })->join(); 514 515 print(ref($foo), "\n"); # Prints 'Yin' 516 print(ref($foo->{'bar'}), "\n"); # Prints 'Yang' 517 print(ref($bar), "\n"); # Also prints 'Yang' 518 519=head1 NOTES 520 521L<threads::shared> is designed to disable itself silently if threads are not 522available. This allows you to write modules and packages that can be used 523in both threaded and non-threaded applications. 524 525If you want access to threads, you must C<use threads> before you 526C<use threads::shared>. L<threads> will emit a warning if you use it after 527L<threads::shared>. 528 529=head1 WARNINGS 530 531=over 4 532 533=item cond_broadcast() called on unlocked variable 534 535=item cond_signal() called on unlocked variable 536 537See L</"cond_signal VARIABLE">, above. 538 539=back 540 541=head1 BUGS AND LIMITATIONS 542 543When C<share> is used on arrays, hashes, array refs or hash refs, any data 544they contain will be lost. 545 546 my @arr = qw(foo bar baz); 547 share(@arr); 548 # @arr is now empty (i.e., == ()); 549 550 # Create a 'foo' object 551 my $foo = { 'data' => 99 }; 552 bless($foo, 'foo'); 553 554 # Share the object 555 share($foo); # Contents are now wiped out 556 print("ERROR: \$foo is empty\n") 557 if (! exists($foo->{'data'})); 558 559Therefore, populate such variables B<after> declaring them as shared. (Scalar 560and scalar refs are not affected by this problem.) 561 562Blessing a shared item after it has been nested in another shared item does 563not propagate the blessing to the shared reference: 564 565 my $foo = &share({}); 566 my $bar = &share({}); 567 $bar->{foo} = $foo; 568 bless($foo, 'baz'); # $foo is now of class 'baz', 569 # but $bar->{foo} is unblessed. 570 571Therefore, you should bless objects before sharing them. 572 573It is often not wise to share an object unless the class itself has been 574written to support sharing. For example, a shared object's destructor may 575get called multiple times, once for each thread's scope exit, or may not 576get called at all if it is embedded inside another shared object. Another 577issue is that the contents of hash-based objects will be lost due to the 578above mentioned limitation. See F<examples/class.pl> (in the CPAN 579distribution of this module) for how to create a class that supports object 580sharing. 581 582Destructors may not be called on objects if those objects still exist at 583global destruction time. If the destructors must be called, make sure 584there are no circular references and that nothing is referencing the 585objects before the program ends. 586 587Does not support C<splice> on arrays. Does not support explicitly changing 588array lengths via $#array -- use C<push> and C<pop> instead. 589 590Taking references to the elements of shared arrays and hashes does not 591autovivify the elements, and neither does slicing a shared array/hash over 592non-existent indices/keys autovivify the elements. 593 594C<share()> allows you to C<< share($hashref->{key}) >> and 595C<< share($arrayref->[idx]) >> without giving any error message. But the 596C<< $hashref->{key} >> or C<< $arrayref->[idx] >> is B<not> shared, causing 597the error "lock can only be used on shared values" to occur when you attempt 598to C<< lock($hashref->{key}) >> or C<< lock($arrayref->[idx]) >> in another 599thread. 600 601Using C<refaddr()> is unreliable for testing 602whether or not two shared references are equivalent (e.g., when testing for 603circular references). Use L<is_shared()|/"is_shared VARIABLE">, instead: 604 605 use threads; 606 use threads::shared; 607 use Scalar::Util qw(refaddr); 608 609 # If ref is shared, use threads::shared's internal ID. 610 # Otherwise, use refaddr(). 611 my $addr1 = is_shared($ref1) || refaddr($ref1); 612 my $addr2 = is_shared($ref2) || refaddr($ref2); 613 614 if ($addr1 == $addr2) { 615 # The refs are equivalent 616 } 617 618L<each()|perlfunc/"each HASH"> does not work properly on shared references 619embedded in shared structures. For example: 620 621 my %foo :shared; 622 $foo{'bar'} = shared_clone({'a'=>'x', 'b'=>'y', 'c'=>'z'}); 623 624 while (my ($key, $val) = each(%{$foo{'bar'}})) { 625 ... 626 } 627 628Either of the following will work instead: 629 630 my $ref = $foo{'bar'}; 631 while (my ($key, $val) = each(%{$ref})) { 632 ... 633 } 634 635 foreach my $key (keys(%{$foo{'bar'}})) { 636 my $val = $foo{'bar'}{$key}; 637 ... 638 } 639 640This module supports dual-valued variables created using C<dualvar()> from 641L<Scalar::Util>. However, while C<$!> acts 642like a dualvar, it is implemented as a tied SV. To propagate its value, use 643the follow construct, if needed: 644 645 my $errno :shared = dualvar($!,$!); 646 647View existing bug reports at, and submit any new bugs, problems, patches, etc. 648to: L<http://rt.cpan.org/Public/Dist/Display.html?Name=threads-shared> 649 650=head1 SEE ALSO 651 652threads::shared on MetaCPAN: 653L<https://metacpan.org/release/threads-shared> 654 655Code repository for CPAN distribution: 656L<https://github.com/Dual-Life/threads-shared> 657 658L<threads>, L<perlthrtut> 659 660L<http://www.perl.com/pub/a/2002/06/11/threads.html> and 661L<http://www.perl.com/pub/a/2002/09/04/threads.html> 662 663Perl threads mailing list: 664L<http://lists.perl.org/list/ithreads.html> 665 666Sample code in the I<examples> directory of this distribution on CPAN. 667 668=head1 AUTHOR 669 670Artur Bergman E<lt>sky AT crucially DOT netE<gt> 671 672Documentation borrowed from the old Thread.pm. 673 674CPAN version produced by Jerry D. Hedden E<lt>jdhedden AT cpan DOT orgE<gt>. 675 676=head1 LICENSE 677 678threads::shared is released under the same license as Perl. 679 680=cut 681