shared.pm 19 KB

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