1threads::shared(3pm) Perl Programmers Reference Guide threads::shared(3pm)
2
3
4
6 threads::shared - Perl extension for sharing data structures between
7 threads
8
10 This document describes threads::shared version 1.32
11
13 use threads;
14 use threads::shared;
15
16 my $var :shared;
17 my %hsh :shared;
18 my @ary :shared;
19
20 my ($scalar, @array, %hash);
21 share($scalar);
22 share(@array);
23 share(%hash);
24
25 $var = $scalar_value;
26 $var = $shared_ref_value;
27 $var = shared_clone($non_shared_ref_value);
28 $var = shared_clone({'foo' => [qw/foo bar baz/]});
29
30 $hsh{'foo'} = $scalar_value;
31 $hsh{'bar'} = $shared_ref_value;
32 $hsh{'baz'} = shared_clone($non_shared_ref_value);
33 $hsh{'quz'} = shared_clone([1..3]);
34
35 $ary[0] = $scalar_value;
36 $ary[1] = $shared_ref_value;
37 $ary[2] = shared_clone($non_shared_ref_value);
38 $ary[3] = shared_clone([ {}, [] ]);
39
40 { lock(%hash); ... }
41
42 cond_wait($scalar);
43 cond_timedwait($scalar, time() + 30);
44 cond_broadcast(@array);
45 cond_signal(%hash);
46
47 my $lockvar :shared;
48 # condition var != lock var
49 cond_wait($var, $lockvar);
50 cond_timedwait($var, time()+30, $lockvar);
51
53 By default, variables are private to each thread, and each newly
54 created thread gets a private copy of each existing variable. This
55 module allows you to share variables across different threads (and
56 pseudo-forks on Win32). It is used together with the threads module.
57
58 This module supports the sharing of the following data types only:
59 scalars and scalar refs, arrays and array refs, and hashes and hash
60 refs.
61
63 The following functions are exported by this module: "share",
64 "shared_clone", "is_shared", "cond_wait", "cond_timedwait",
65 "cond_signal" and "cond_broadcast"
66
67 Note that if this module is imported when threads has not yet been
68 loaded, then these functions all become no-ops. This makes it possible
69 to write modules that will work in both threaded and non-threaded
70 environments.
71
73 share VARIABLE
74 "share" takes a variable and marks it as shared:
75
76 my ($scalar, @array, %hash);
77 share($scalar);
78 share(@array);
79 share(%hash);
80
81 "share" will return the shared rvalue, but always as a reference.
82
83 Variables can also be marked as shared at compile time by using the
84 ":shared" attribute:
85
86 my ($var, %hash, @array) :shared;
87
88 Shared variables can only store scalars, refs of shared variables,
89 or refs of shared data (discussed in next section):
90
91 my ($var, %hash, @array) :shared;
92 my $bork;
93
94 # Storing scalars
95 $var = 1;
96 $hash{'foo'} = 'bar';
97 $array[0] = 1.5;
98
99 # Storing shared refs
100 $var = \%hash;
101 $hash{'ary'} = \@array;
102 $array[1] = \$var;
103
104 # The following are errors:
105 # $var = \$bork; # ref of non-shared variable
106 # $hash{'bork'} = []; # non-shared array ref
107 # push(@array, { 'x' => 1 }); # non-shared hash ref
108
109 shared_clone REF
110 "shared_clone" takes a reference, and returns a shared version of
111 its argument, performing a deep copy on any non-shared elements.
112 Any shared elements in the argument are used as is (i.e., they are
113 not cloned).
114
115 my $cpy = shared_clone({'foo' => [qw/foo bar baz/]});
116
117 Object status (i.e., the class an object is blessed into) is also
118 cloned.
119
120 my $obj = {'foo' => [qw/foo bar baz/]};
121 bless($obj, 'Foo');
122 my $cpy = shared_clone($obj);
123 print(ref($cpy), "\n"); # Outputs 'Foo'
124
125 For cloning empty array or hash refs, the following may also be
126 used:
127
128 $var = &share([]); # Same as $var = shared_clone([]);
129 $var = &share({}); # Same as $var = shared_clone({});
130
131 is_shared VARIABLE
132 "is_shared" checks if the specified variable is shared or not. If
133 shared, returns the variable's internal ID (similar to refaddr()).
134 Otherwise, returns "undef".
135
136 if (is_shared($var)) {
137 print("\$var is shared\n");
138 } else {
139 print("\$var is not shared\n");
140 }
141
142 When used on an element of an array or hash, "is_shared" checks if
143 the specified element belongs to a shared array or hash. (It does
144 not check the contents of that element.)
145
146 my %hash :shared;
147 if (is_shared(%hash)) {
148 print("\%hash is shared\n");
149 }
150
151 $hash{'elem'} = 1;
152 if (is_shared($hash{'elem'})) {
153 print("\$hash{'elem'} is in a shared hash\n");
154 }
155
156 lock VARIABLE
157 "lock" places a advisory lock on a variable until the lock goes out
158 of scope. If the variable is locked by another thread, the "lock"
159 call will block until it's available. Multiple calls to "lock" by
160 the same thread from within dynamically nested scopes are safe --
161 the variable will remain locked until the outermost lock on the
162 variable goes out of scope.
163
164 "lock" follows references exactly one level:
165
166 my %hash :shared;
167 my $ref = \%hash;
168 lock($ref); # This is equivalent to lock(%hash)
169
170 Note that you cannot explicitly unlock a variable; you can only
171 wait for the lock to go out of scope. This is most easily
172 accomplished by locking the variable inside a block.
173
174 my $var :shared;
175 {
176 lock($var);
177 # $var is locked from here to the end of the block
178 ...
179 }
180 # $var is now unlocked
181
182 As locks are advisory, they do not prevent data access or
183 modification by another thread that does not itself attempt to
184 obtain a lock on the variable.
185
186 You cannot lock the individual elements of a container variable:
187
188 my %hash :shared;
189 $hash{'foo'} = 'bar';
190 #lock($hash{'foo'}); # Error
191 lock(%hash); # Works
192
193 If you need more fine-grained control over shared variable access,
194 see Thread::Semaphore.
195
196 cond_wait VARIABLE
197 cond_wait CONDVAR, LOCKVAR
198 The "cond_wait" function takes a locked variable as a parameter,
199 unlocks the variable, and blocks until another thread does a
200 "cond_signal" or "cond_broadcast" for that same locked variable.
201 The variable that "cond_wait" blocked on is relocked after the
202 "cond_wait" is satisfied. If there are multiple threads
203 "cond_wait"ing on the same variable, all but one will re-block
204 waiting to reacquire the lock on the variable. (So if you're only
205 using "cond_wait" for synchronisation, give up the lock as soon as
206 possible). The two actions of unlocking the variable and entering
207 the blocked wait state are atomic, the two actions of exiting from
208 the blocked wait state and re-locking the variable are not.
209
210 In its second form, "cond_wait" takes a shared, unlocked variable
211 followed by a shared, locked variable. The second variable is
212 unlocked and thread execution suspended until another thread
213 signals the first variable.
214
215 It is important to note that the variable can be notified even if
216 no thread "cond_signal" or "cond_broadcast" on the variable. It is
217 therefore important to check the value of the variable and go back
218 to waiting if the requirement is not fulfilled. For example, to
219 pause until a shared counter drops to zero:
220
221 { lock($counter); cond_wait($counter) until $counter == 0; }
222
223 cond_timedwait VARIABLE, ABS_TIMEOUT
224 cond_timedwait CONDVAR, ABS_TIMEOUT, LOCKVAR
225 In its two-argument form, "cond_timedwait" takes a locked variable
226 and an absolute timeout as parameters, unlocks the variable, and
227 blocks until the timeout is reached or another thread signals the
228 variable. A false value is returned if the timeout is reached, and
229 a true value otherwise. In either case, the variable is re-locked
230 upon return.
231
232 Like "cond_wait", this function may take a shared, locked variable
233 as an additional parameter; in this case the first parameter is an
234 unlocked condition variable protected by a distinct lock variable.
235
236 Again like "cond_wait", waking up and reacquiring the lock are not
237 atomic, and you should always check your desired condition after
238 this function returns. Since the timeout is an absolute value,
239 however, it does not have to be recalculated with each pass:
240
241 lock($var);
242 my $abs = time() + 15;
243 until ($ok = desired_condition($var)) {
244 last if !cond_timedwait($var, $abs);
245 }
246 # we got it if $ok, otherwise we timed out!
247
248 cond_signal VARIABLE
249 The "cond_signal" function takes a locked variable as a parameter
250 and unblocks one thread that's "cond_wait"ing on that variable. If
251 more than one thread is blocked in a "cond_wait" on that variable,
252 only one (and which one is indeterminate) will be unblocked.
253
254 If there are no threads blocked in a "cond_wait" on the variable,
255 the signal is discarded. By always locking before signaling, you
256 can (with care), avoid signaling before another thread has entered
257 cond_wait().
258
259 "cond_signal" will normally generate a warning if you attempt to
260 use it on an unlocked variable. On the rare occasions where doing
261 this may be sensible, you can suppress the warning with:
262
263 { no warnings 'threads'; cond_signal($foo); }
264
265 cond_broadcast VARIABLE
266 The "cond_broadcast" function works similarly to "cond_signal".
267 "cond_broadcast", though, will unblock all the threads that are
268 blocked in a "cond_wait" on the locked variable, rather than only
269 one.
270
272 threads::shared exports a version of bless() that works on shared
273 objects such that blessings propagate across threads.
274
275 # Create a shared 'Foo' object
276 my $foo :shared = shared_clone({});
277 bless($foo, 'Foo');
278
279 # Create a shared 'Bar' object
280 my $bar :shared = shared_clone({});
281 bless($bar, 'Bar');
282
283 # Put 'bar' inside 'foo'
284 $foo->{'bar'} = $bar;
285
286 # Rebless the objects via a thread
287 threads->create(sub {
288 # Rebless the outer object
289 bless($foo, 'Yin');
290
291 # Cannot directly rebless the inner object
292 #bless($foo->{'bar'}, 'Yang');
293
294 # Retrieve and rebless the inner object
295 my $obj = $foo->{'bar'};
296 bless($obj, 'Yang');
297 $foo->{'bar'} = $obj;
298
299 })->join();
300
301 print(ref($foo), "\n"); # Prints 'Yin'
302 print(ref($foo->{'bar'}), "\n"); # Prints 'Yang'
303 print(ref($bar), "\n"); # Also prints 'Yang'
304
306 threads::shared is designed to disable itself silently if threads are
307 not available. This allows you to write modules and packages that can
308 be used in both threaded and non-threaded applications.
309
310 If you want access to threads, you must "use threads" before you "use
311 threads::shared". threads will emit a warning if you use it after
312 threads::shared.
313
315 When "share" is used on arrays, hashes, array refs or hash refs, any
316 data they contain will be lost.
317
318 my @arr = qw(foo bar baz);
319 share(@arr);
320 # @arr is now empty (i.e., == ());
321
322 # Create a 'foo' object
323 my $foo = { 'data' => 99 };
324 bless($foo, 'foo');
325
326 # Share the object
327 share($foo); # Contents are now wiped out
328 print("ERROR: \$foo is empty\n")
329 if (! exists($foo->{'data'}));
330
331 Therefore, populate such variables after declaring them as shared.
332 (Scalar and scalar refs are not affected by this problem.)
333
334 It is often not wise to share an object unless the class itself has
335 been written to support sharing. For example, an object's destructor
336 may get called multiple times, once for each thread's scope exit.
337 Another danger is that the contents of hash-based objects will be lost
338 due to the above mentioned limitation. See examples/class.pl (in the
339 CPAN distribution of this module) for how to create a class that
340 supports object sharing.
341
342 Does not support "splice" on arrays!
343
344 Taking references to the elements of shared arrays and hashes does not
345 autovivify the elements, and neither does slicing a shared array/hash
346 over non-existent indices/keys autovivify the elements.
347
348 "share()" allows you to "share($hashref->{key})" and
349 "share($arrayref->[idx])" without giving any error message. But the
350 "$hashref->{key}" or "$arrayref->[idx]" is not shared, causing the
351 error "lock can only be used on shared values" to occur when you
352 attempt to "lock($hasref->{key})" or "lock($arrayref->[idx])" in
353 another thread.
354
355 Using refaddr()) is unreliable for testing whether or not two shared
356 references are equivalent (e.g., when testing for circular references).
357 Use "is_shared VARIABLE" in is_shared(), instead:
358
359 use threads;
360 use threads::shared;
361 use Scalar::Util qw(refaddr);
362
363 # If ref is shared, use threads::shared's internal ID.
364 # Otherwise, use refaddr().
365 my $addr1 = is_shared($ref1) || refaddr($ref1);
366 my $addr2 = is_shared($ref2) || refaddr($ref2);
367
368 if ($addr1 == $addr2) {
369 # The refs are equivalent
370 }
371
372 each() does not work properly on shared references embedded in shared
373 structures. For example:
374
375 my %foo :shared;
376 $foo{'bar'} = shared_clone({'a'=>'x', 'b'=>'y', 'c'=>'z'});
377
378 while (my ($key, $val) = each(%{$foo{'bar'}})) {
379 ...
380 }
381
382 Either of the following will work instead:
383
384 my $ref = $foo{'bar'};
385 while (my ($key, $val) = each(%{$ref})) {
386 ...
387 }
388
389 foreach my $key (keys(%{$foo{'bar'}})) {
390 my $val = $foo{'bar'}{$key};
391 ...
392 }
393
394 View existing bug reports at, and submit any new bugs, problems,
395 patches, etc. to:
396 http://rt.cpan.org/Public/Dist/Display.html?Name=threads-shared
397 <http://rt.cpan.org/Public/Dist/Display.html?Name=threads-shared>
398
400 threads::shared Discussion Forum on CPAN:
401 http://www.cpanforum.com/dist/threads-shared
402 <http://www.cpanforum.com/dist/threads-shared>
403
404 Annotated POD for threads::shared:
405 http://annocpan.org/~JDHEDDEN/threads-shared-1.32/shared.pm
406 <http://annocpan.org/~JDHEDDEN/threads-shared-1.32/shared.pm>
407
408 Source repository: http://code.google.com/p/threads-shared/
409 <http://code.google.com/p/threads-shared/>
410
411 threads, perlthrtut
412
413 <http://www.perl.com/pub/a/2002/06/11/threads.html> and
414 <http://www.perl.com/pub/a/2002/09/04/threads.html>
415
416 Perl threads mailing list:
417 <http://lists.cpan.org/showlist.cgi?name=iThreads>
418
420 Artur Bergman <sky AT crucially DOT net>
421
422 Documentation borrowed from the old Thread.pm.
423
424 CPAN version produced by Jerry D. Hedden <jdhedden AT cpan DOT org>.
425
427 threads::shared is released under the same license as Perl.
428
429
430
431perl v5.12.4 2011-06-20 threads::shared(3pm)