Commit | Line | Data |
---|---|---|
b050c948 | 1 | package threads::shared; |
73e09c8f | 2 | |
c46325ea | 3 | use 5.008; |
7473853a | 4 | |
b050c948 AB |
5 | use strict; |
6 | use warnings; | |
73e09c8f | 7 | |
f6d55995 | 8 | our $VERSION = '1.19'; |
7473853a SP |
9 | my $XS_VERSION = $VERSION; |
10 | $VERSION = eval $VERSION; | |
11 | ||
12 | # Declare that we have been loaded | |
13 | $threads::shared::threads_shared = 1; | |
14 | ||
15 | # Load the XS code, if applicable | |
16 | if ($threads::threads) { | |
17 | require XSLoader; | |
18 | XSLoader::load('threads::shared', $XS_VERSION); | |
19 | ||
20 | *is_shared = \&_id; | |
21 | ||
22 | } else { | |
23 | # String eval is generally evil, but we don't want these subs to | |
24 | # exist at all if 'threads' is not loaded successfully. | |
25 | # Vivifying them conditionally this way saves on average about 4K | |
26 | # of memory per thread. | |
27 | eval <<'_MARKER_'; | |
28 | sub share (\[$@%]) { return $_[0] } | |
29 | sub is_shared (\[$@%]) { undef } | |
30 | sub cond_wait (\[$@%];\[$@%]) { undef } | |
31 | sub cond_timedwait (\[$@%]$;\[$@%]) { undef } | |
32 | sub cond_signal (\[$@%]) { undef } | |
33 | sub cond_broadcast (\[$@%]) { undef } | |
34 | _MARKER_ | |
35 | } | |
36 | ||
37 | ||
38 | ### Export ### | |
39 | ||
40 | sub import | |
41 | { | |
42 | # Exported subroutines | |
43 | my @EXPORT = qw(share is_shared cond_wait cond_timedwait | |
44 | cond_signal cond_broadcast); | |
5c360ac5 | 45 | if ($threads::threads) { |
7473853a | 46 | push(@EXPORT, 'bless'); |
5c360ac5 | 47 | } |
7473853a SP |
48 | |
49 | # Export subroutine names | |
50 | my $caller = caller(); | |
51 | foreach my $sym (@EXPORT) { | |
52 | no strict 'refs'; | |
53 | *{$caller.'::'.$sym} = \&{$sym}; | |
df5c998e EM |
54 | } |
55 | } | |
b050c948 | 56 | |
7473853a SP |
57 | |
58 | ### Methods, etc. ### | |
dab065ea | 59 | |
6b85e4fe NIS |
60 | sub threads::shared::tie::SPLICE |
61 | { | |
7473853a SP |
62 | require Carp; |
63 | Carp::croak('Splice not implemented for shared arrays'); | |
6b85e4fe NIS |
64 | } |
65 | ||
7473853a SP |
66 | 1; |
67 | ||
b050c948 AB |
68 | __END__ |
69 | ||
70 | =head1 NAME | |
71 | ||
72 | threads::shared - Perl extension for sharing data structures between threads | |
73 | ||
7473853a SP |
74 | =head1 VERSION |
75 | ||
f6d55995 | 76 | This document describes threads::shared version 1.19 |
7473853a | 77 | |
b050c948 AB |
78 | =head1 SYNOPSIS |
79 | ||
73e09c8f | 80 | use threads; |
b050c948 AB |
81 | use threads::shared; |
82 | ||
7473853a | 83 | my $var :shared; |
ca5ff8b2 DM |
84 | $var = $scalar_value; |
85 | $var = $shared_ref_value; | |
7473853a | 86 | $var = share($simple_unshared_ref_value); |
38875929 | 87 | |
3b29be8d | 88 | my ($scalar, @array, %hash); |
4cab98c0 SG |
89 | share($scalar); |
90 | share(@array); | |
aaf3876d | 91 | share(%hash); |
caf25f3b AB |
92 | my $bar = &share([]); |
93 | $hash{bar} = &share({}); | |
b050c948 | 94 | |
38875929 DM |
95 | { lock(%hash); ... } |
96 | ||
b050c948 | 97 | cond_wait($scalar); |
a0e036c1 | 98 | cond_timedwait($scalar, time() + 30); |
515f0976 AB |
99 | cond_broadcast(@array); |
100 | cond_signal(%hash); | |
b050c948 | 101 | |
7473853a | 102 | my $lockvar :shared; |
a0e036c1 MP |
103 | # condition var != lock var |
104 | cond_wait($var, $lockvar); | |
105 | cond_timedwait($var, time()+30, $lockvar); | |
106 | ||
b050c948 AB |
107 | =head1 DESCRIPTION |
108 | ||
38875929 | 109 | By default, variables are private to each thread, and each newly created |
7473853a | 110 | thread gets a private copy of each existing variable. This module allows you |
7c8caac0 | 111 | to share variables across different threads (and pseudo-forks on Win32). It is |
7473853a | 112 | used together with the L<threads> module. |
b050c948 | 113 | |
515f0976 | 114 | =head1 EXPORT |
b050c948 | 115 | |
7473853a SP |
116 | C<share>, C<cond_wait>, C<cond_timedwait>, C<cond_signal>, C<cond_broadcast>, |
117 | C<is_shared> | |
515f0976 | 118 | |
7473853a SP |
119 | Note that if this module is imported when L<threads> has not yet been loaded, |
120 | then these functions all become no-ops. This makes it possible to write | |
121 | modules that will work in both threaded and non-threaded environments. | |
e67b86b3 | 122 | |
515f0976 AB |
123 | =head1 FUNCTIONS |
124 | ||
125 | =over 4 | |
126 | ||
127 | =item share VARIABLE | |
128 | ||
7473853a SP |
129 | C<share> takes a value and marks it as shared. You can share a scalar, array, |
130 | hash, scalar ref, array ref, or hash ref. C<share> will return the shared | |
131 | rvalue, but always as a reference. | |
515f0976 | 132 | |
38875929 | 133 | A variable can also be marked as shared at compile time by using the |
7473853a | 134 | C<:shared> attribute: C<my $var :shared;>. |
38875929 | 135 | |
7473853a SP |
136 | Due to problems with Perl's prototyping, if you want to share a newly created |
137 | reference, you need to use the C<&share([])> and C<&share({})> syntax. | |
caf25f3b | 138 | |
ca5ff8b2 | 139 | The only values that can be assigned to a shared scalar are other scalar |
7473853a SP |
140 | values, or shared refs: |
141 | ||
142 | my $var :shared; | |
143 | $var = 1; # ok | |
144 | $var = []; # error | |
145 | $var = &share([]); # ok | |
146 | ||
147 | C<share> will traverse up references exactly I<one> level. C<share(\$a)> is | |
148 | equivalent to C<share($a)>, while C<share(\\$a)> is not. This means that you | |
149 | must create nested shared data structures by first creating individual shared | |
150 | leaf nodes, and then adding them to a shared hash or array. | |
ca5ff8b2 | 151 | |
7473853a SP |
152 | my %hash :shared; |
153 | $hash{'meaning'} = &share([]); | |
154 | $hash{'meaning'}[0] = &share({}); | |
155 | $hash{'meaning'}[0]{'life'} = 42; | |
ca5ff8b2 | 156 | |
7473853a SP |
157 | =item is_shared VARIABLE |
158 | ||
159 | C<is_shared> checks if the specified variable is shared or not. If shared, | |
160 | returns the variable's internal ID (similar to | |
161 | L<refaddr()|Scalar::Util/"refaddr EXPR">). Otherwise, returns C<undef>. | |
162 | ||
163 | if (is_shared($var)) { | |
164 | print("\$var is shared\n"); | |
165 | } else { | |
166 | print("\$var is not shared\n"); | |
167 | } | |
ca5ff8b2 | 168 | |
515f0976 AB |
169 | =item lock VARIABLE |
170 | ||
7473853a SP |
171 | C<lock> places a lock on a variable until the lock goes out of scope. If the |
172 | variable is locked by another thread, the C<lock> call will block until it's | |
2b936299 RGS |
173 | available. Multiple calls to C<lock> by the same thread from within |
174 | dynamically nested scopes are safe -- the variable will remain locked until | |
175 | the outermost lock on the variable goes out of scope. | |
7473853a | 176 | |
2b936299 RGS |
177 | Locking a container object, such as a hash or array, doesn't lock the elements |
178 | of that container. For example, if a thread does a C<lock(@a)>, any other | |
179 | thread doing a C<lock($a[12])> won't block. | |
515f0976 | 180 | |
2b936299 RGS |
181 | C<lock()> follows references exactly I<one> level. C<lock(\$a)> is equivalent |
182 | to C<lock($a)>, while C<lock(\\$a)> is not. | |
515f0976 | 183 | |
7473853a SP |
184 | Note that you cannot explicitly unlock a variable; you can only wait for the |
185 | lock to go out of scope. This is most easily accomplished by locking the | |
186 | variable inside a block. | |
515f0976 | 187 | |
7473853a SP |
188 | my $var :shared; |
189 | { | |
190 | lock($var); | |
191 | # $var is locked from here to the end of the block | |
192 | ... | |
193 | } | |
194 | # $var is now unlocked | |
195 | ||
196 | If you need more fine-grained control over shared variable access, see | |
197 | L<Thread::Semaphore>. | |
515f0976 AB |
198 | |
199 | =item cond_wait VARIABLE | |
200 | ||
a0e036c1 MP |
201 | =item cond_wait CONDVAR, LOCKVAR |
202 | ||
7473853a SP |
203 | The C<cond_wait> function takes a B<locked> variable as a parameter, unlocks |
204 | the variable, and blocks until another thread does a C<cond_signal> or | |
205 | C<cond_broadcast> for that same locked variable. The variable that | |
206 | C<cond_wait> blocked on is relocked after the C<cond_wait> is satisfied. If | |
207 | there are multiple threads C<cond_wait>ing on the same variable, all but one | |
7c8caac0 | 208 | will re-block waiting to reacquire the lock on the variable. (So if you're only |
7473853a SP |
209 | using C<cond_wait> for synchronisation, give up the lock as soon as possible). |
210 | The two actions of unlocking the variable and entering the blocked wait state | |
211 | are atomic, the two actions of exiting from the blocked wait state and | |
7c8caac0 | 212 | re-locking the variable are not. |
7473853a SP |
213 | |
214 | In its second form, C<cond_wait> takes a shared, B<unlocked> variable followed | |
215 | by a shared, B<locked> variable. The second variable is unlocked and thread | |
216 | execution suspended until another thread signals the first variable. | |
217 | ||
218 | It is important to note that the variable can be notified even if no thread | |
219 | C<cond_signal> or C<cond_broadcast> on the variable. It is therefore | |
220 | important to check the value of the variable and go back to waiting if the | |
221 | requirement is not fulfilled. For example, to pause until a shared counter | |
222 | drops to zero: | |
223 | ||
224 | { lock($counter); cond_wait($count) until $counter == 0; } | |
a0e036c1 MP |
225 | |
226 | =item cond_timedwait VARIABLE, ABS_TIMEOUT | |
227 | ||
228 | =item cond_timedwait CONDVAR, ABS_TIMEOUT, LOCKVAR | |
229 | ||
7473853a SP |
230 | In its two-argument form, C<cond_timedwait> takes a B<locked> variable and an |
231 | absolute timeout as parameters, unlocks the variable, and blocks until the | |
232 | timeout is reached or another thread signals the variable. A false value is | |
233 | returned if the timeout is reached, and a true value otherwise. In either | |
234 | case, the variable is re-locked upon return. | |
a0e036c1 | 235 | |
7473853a SP |
236 | Like C<cond_wait>, this function may take a shared, B<locked> variable as an |
237 | additional parameter; in this case the first parameter is an B<unlocked> | |
238 | condition variable protected by a distinct lock variable. | |
a0e036c1 | 239 | |
7473853a SP |
240 | Again like C<cond_wait>, waking up and reacquiring the lock are not atomic, |
241 | and you should always check your desired condition after this function | |
242 | returns. Since the timeout is an absolute value, however, it does not have to | |
243 | be recalculated with each pass: | |
a0e036c1 | 244 | |
7473853a SP |
245 | lock($var); |
246 | my $abs = time() + 15; | |
247 | until ($ok = desired_condition($var)) { | |
a0e036c1 | 248 | last if !cond_timedwait($var, $abs); |
7473853a SP |
249 | } |
250 | # we got it if $ok, otherwise we timed out! | |
515f0976 AB |
251 | |
252 | =item cond_signal VARIABLE | |
253 | ||
7473853a SP |
254 | The C<cond_signal> function takes a B<locked> variable as a parameter and |
255 | unblocks one thread that's C<cond_wait>ing on that variable. If more than one | |
256 | thread is blocked in a C<cond_wait> on that variable, only one (and which one | |
257 | is indeterminate) will be unblocked. | |
515f0976 | 258 | |
7473853a SP |
259 | If there are no threads blocked in a C<cond_wait> on the variable, the signal |
260 | is discarded. By always locking before signaling, you can (with care), avoid | |
261 | signaling before another thread has entered cond_wait(). | |
38875929 | 262 | |
7473853a SP |
263 | C<cond_signal> will normally generate a warning if you attempt to use it on an |
264 | unlocked variable. On the rare occasions where doing this may be sensible, you | |
ba2940ce | 265 | can suppress the warning with: |
38875929 | 266 | |
7473853a | 267 | { no warnings 'threads'; cond_signal($foo); } |
515f0976 AB |
268 | |
269 | =item cond_broadcast VARIABLE | |
270 | ||
271 | The C<cond_broadcast> function works similarly to C<cond_signal>. | |
7473853a SP |
272 | C<cond_broadcast>, though, will unblock B<all> the threads that are blocked in |
273 | a C<cond_wait> on the locked variable, rather than only one. | |
b050c948 | 274 | |
4cab98c0 | 275 | =back |
dab065ea | 276 | |
7473853a SP |
277 | =head1 OBJECTS |
278 | ||
279 | L<threads::shared> exports a version of L<bless()|perlfunc/"bless REF"> that | |
2b936299 | 280 | works on shared objects such that I<blessings> propagate across threads. |
7473853a SP |
281 | |
282 | # Create a shared 'foo' object | |
283 | my $foo; | |
284 | share($foo); | |
285 | $foo = &share({}); | |
286 | bless($foo, 'foo'); | |
287 | ||
288 | # Create a shared 'bar' object | |
289 | my $bar; | |
290 | share($bar); | |
291 | $bar = &share({}); | |
292 | bless($bar, 'bar'); | |
293 | ||
294 | # Put 'bar' inside 'foo' | |
295 | $foo->{'bar'} = $bar; | |
296 | ||
297 | # Rebless the objects via a thread | |
298 | threads->create(sub { | |
299 | # Rebless the outer object | |
300 | bless($foo, 'yin'); | |
301 | ||
302 | # Cannot directly rebless the inner object | |
303 | #bless($foo->{'bar'}, 'yang'); | |
304 | ||
305 | # Retrieve and rebless the inner object | |
306 | my $obj = $foo->{'bar'}; | |
307 | bless($obj, 'yang'); | |
308 | $foo->{'bar'} = $obj; | |
309 | ||
310 | })->join(); | |
311 | ||
312 | print(ref($foo), "\n"); # Prints 'yin' | |
313 | print(ref($foo->{'bar'}), "\n"); # Prints 'yang' | |
314 | print(ref($bar), "\n"); # Also prints 'yang' | |
315 | ||
dab065ea AB |
316 | =head1 NOTES |
317 | ||
33d16ee7 JH |
318 | L<threads::shared> is designed to disable itself silently if threads are not |
319 | available. This allows you to write modules and packages that can be used | |
320 | in both threaded and non-threaded applications. | |
321 | ||
322 | If you want access to threads, you must C<use threads> before you | |
7473853a SP |
323 | C<use threads::shared>. L<threads> will emit a warning if you use it after |
324 | L<threads::shared>. | |
dab065ea | 325 | |
7473853a | 326 | =head1 BUGS AND LIMITATIONS |
b050c948 | 327 | |
7473853a SP |
328 | When C<share> is used on arrays, hashes, array refs or hash refs, any data |
329 | they contain will be lost. | |
515f0976 | 330 | |
7473853a SP |
331 | my @arr = qw(foo bar baz); |
332 | share(@arr); | |
333 | # @arr is now empty (i.e., == ()); | |
b050c948 | 334 | |
7473853a SP |
335 | # Create a 'foo' object |
336 | my $foo = { 'data' => 99 }; | |
337 | bless($foo, 'foo'); | |
58122748 | 338 | |
7473853a SP |
339 | # Share the object |
340 | share($foo); # Contents are now wiped out | |
341 | print("ERROR: \$foo is empty\n") | |
342 | if (! exists($foo->{'data'})); | |
3d32476b | 343 | |
7473853a SP |
344 | Therefore, populate such variables B<after> declaring them as shared. (Scalar |
345 | and scalar refs are not affected by this problem.) | |
346 | ||
347 | It is often not wise to share an object unless the class itself has been | |
2b936299 RGS |
348 | written to support sharing. For example, an object's destructor may get |
349 | called multiple times, once for each thread's scope exit. Another danger is | |
350 | that the contents of hash-based objects will be lost due to the above | |
351 | mentioned limitation. See F<examples/class.pl> (in the CPAN distribution of | |
352 | this module) for how to create a class that supports object sharing. | |
b050c948 | 353 | |
7473853a | 354 | Does not support C<splice> on arrays! |
b050c948 | 355 | |
7473853a SP |
356 | Taking references to the elements of shared arrays and hashes does not |
357 | autovivify the elements, and neither does slicing a shared array/hash over | |
358 | non-existent indices/keys autovivify the elements. | |
359 | ||
360 | C<share()> allows you to C<< share($hashref->{key}) >> without giving any | |
361 | error message. But the C<< $hashref->{key} >> is B<not> shared, causing the | |
362 | error "locking can only be used on shared values" to occur when you attempt to | |
363 | C<< lock($hasref->{key}) >>. | |
b050c948 | 364 | |
f6d55995 JH |
365 | Using L<refaddr()|Scalar::Util/"refaddr EXPR">) is unreliable for testing |
366 | whether or not two shared references are equivalent (e.g., when testing for | |
367 | circular references). Use L<is_shared()/"is_shared VARIABLE">, instead: | |
368 | ||
369 | use threads; | |
370 | use threads::shared; | |
371 | use Scalar::Util qw(refaddr); | |
372 | ||
373 | # If ref is shared, use threads::shared's internal ID. | |
374 | # Otherwise, use refaddr(). | |
375 | my $addr1 = is_shared($ref1) || refaddr($ref1); | |
376 | my $addr2 = is_shared($ref2) || refaddr($ref2); | |
377 | ||
378 | if ($addr1 == $addr2) { | |
379 | # The refs are equivalent | |
380 | } | |
381 | ||
7473853a | 382 | View existing bug reports at, and submit any new bugs, problems, patches, etc. |
794f4697 | 383 | to: L<http://rt.cpan.org/Public/Dist/Display.html?Name=threads-shared> |
515f0976 | 384 | |
b050c948 AB |
385 | =head1 SEE ALSO |
386 | ||
7473853a SP |
387 | L<threads::shared> Discussion Forum on CPAN: |
388 | L<http://www.cpanforum.com/dist/threads-shared> | |
389 | ||
390 | Annotated POD for L<threads::shared>: | |
f6d55995 | 391 | L<http://annocpan.org/~JDHEDDEN/threads-shared-1.19/shared.pm> |
05b59262 RGS |
392 | |
393 | Source repository: | |
394 | L<http://code.google.com/p/threads-shared/> | |
7473853a SP |
395 | |
396 | L<threads>, L<perlthrtut> | |
397 | ||
398 | L<http://www.perl.com/pub/a/2002/06/11/threads.html> and | |
399 | L<http://www.perl.com/pub/a/2002/09/04/threads.html> | |
400 | ||
401 | Perl threads mailing list: | |
402 | L<http://lists.cpan.org/showlist.cgi?name=iThreads> | |
403 | ||
404 | =head1 AUTHOR | |
405 | ||
406 | Artur Bergman E<lt>sky AT crucially DOT netE<gt> | |
407 | ||
408 | threads::shared is released under the same license as Perl. | |
409 | ||
410 | Documentation borrowed from the old Thread.pm. | |
411 | ||
412 | CPAN version produced by Jerry D. Hedden E<lt>jdhedden AT cpan DOT orgE<gt>. | |
b050c948 AB |
413 | |
414 | =cut |