1threads::shared(3) User Contributed Perl Documentation threads::shared(3)
2
3
4
6 threads::shared - Perl extension for sharing data structures between
7 threads
8
10 This document describes threads::shared version 1.43
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 Not all Perl data types can be cloned (e.g., globs, code refs). By
132 default, "shared_clone" will croak if it encounters such items. To
133 change this behaviour to a warning, then set the following:
134
135 $threads::shared::clone_warn = 1;
136
137 In this case, "undef" will be substituted for the item to be
138 cloned. If set to zero:
139
140 $threads::shared::clone_warn = 0;
141
142 then the "undef" substitution will be performed silently.
143
144 is_shared VARIABLE
145 "is_shared" checks if the specified variable is shared or not. If
146 shared, returns the variable's internal ID (similar to refaddr()).
147 Otherwise, returns "undef".
148
149 if (is_shared($var)) {
150 print("\$var is shared\n");
151 } else {
152 print("\$var is not shared\n");
153 }
154
155 When used on an element of an array or hash, "is_shared" checks if
156 the specified element belongs to a shared array or hash. (It does
157 not check the contents of that element.)
158
159 my %hash :shared;
160 if (is_shared(%hash)) {
161 print("\%hash is shared\n");
162 }
163
164 $hash{'elem'} = 1;
165 if (is_shared($hash{'elem'})) {
166 print("\$hash{'elem'} is in a shared hash\n");
167 }
168
169 lock VARIABLE
170 "lock" places a advisory lock on a variable until the lock goes out
171 of scope. If the variable is locked by another thread, the "lock"
172 call will block until it's available. Multiple calls to "lock" by
173 the same thread from within dynamically nested scopes are safe --
174 the variable will remain locked until the outermost lock on the
175 variable goes out of scope.
176
177 "lock" follows references exactly one level:
178
179 my %hash :shared;
180 my $ref = \%hash;
181 lock($ref); # This is equivalent to lock(%hash)
182
183 Note that you cannot explicitly unlock a variable; you can only
184 wait for the lock to go out of scope. This is most easily
185 accomplished by locking the variable inside a block.
186
187 my $var :shared;
188 {
189 lock($var);
190 # $var is locked from here to the end of the block
191 ...
192 }
193 # $var is now unlocked
194
195 As locks are advisory, they do not prevent data access or
196 modification by another thread that does not itself attempt to
197 obtain a lock on the variable.
198
199 You cannot lock the individual elements of a container variable:
200
201 my %hash :shared;
202 $hash{'foo'} = 'bar';
203 #lock($hash{'foo'}); # Error
204 lock(%hash); # Works
205
206 If you need more fine-grained control over shared variable access,
207 see Thread::Semaphore.
208
209 cond_wait VARIABLE
210 cond_wait CONDVAR, LOCKVAR
211 The "cond_wait" function takes a locked variable as a parameter,
212 unlocks the variable, and blocks until another thread does a
213 "cond_signal" or "cond_broadcast" for that same locked variable.
214 The variable that "cond_wait" blocked on is re-locked after the
215 "cond_wait" is satisfied. If there are multiple threads
216 "cond_wait"ing on the same variable, all but one will re-block
217 waiting to reacquire the lock on the variable. (So if you're only
218 using "cond_wait" for synchronization, give up the lock as soon as
219 possible). The two actions of unlocking the variable and entering
220 the blocked wait state are atomic, the two actions of exiting from
221 the blocked wait state and re-locking the variable are not.
222
223 In its second form, "cond_wait" takes a shared, unlocked variable
224 followed by a shared, locked variable. The second variable is
225 unlocked and thread execution suspended until another thread
226 signals the first variable.
227
228 It is important to note that the variable can be notified even if
229 no thread "cond_signal" or "cond_broadcast" on the variable. It is
230 therefore important to check the value of the variable and go back
231 to waiting if the requirement is not fulfilled. For example, to
232 pause until a shared counter drops to zero:
233
234 { lock($counter); cond_wait($counter) until $counter == 0; }
235
236 cond_timedwait VARIABLE, ABS_TIMEOUT
237 cond_timedwait CONDVAR, ABS_TIMEOUT, LOCKVAR
238 In its two-argument form, "cond_timedwait" takes a locked variable
239 and an absolute timeout in epoch seconds (see time() in perlfunc
240 for more) as parameters, unlocks the variable, and blocks until the
241 timeout is reached or another thread signals the variable. A false
242 value is returned if the timeout is reached, and a true value
243 otherwise. In either case, the variable is re-locked upon return.
244
245 Like "cond_wait", this function may take a shared, locked variable
246 as an additional parameter; in this case the first parameter is an
247 unlocked condition variable protected by a distinct lock variable.
248
249 Again like "cond_wait", waking up and reacquiring the lock are not
250 atomic, and you should always check your desired condition after
251 this function returns. Since the timeout is an absolute value,
252 however, it does not have to be recalculated with each pass:
253
254 lock($var);
255 my $abs = time() + 15;
256 until ($ok = desired_condition($var)) {
257 last if !cond_timedwait($var, $abs);
258 }
259 # we got it if $ok, otherwise we timed out!
260
261 cond_signal VARIABLE
262 The "cond_signal" function takes a locked variable as a parameter
263 and unblocks one thread that's "cond_wait"ing on that variable. If
264 more than one thread is blocked in a "cond_wait" on that variable,
265 only one (and which one is indeterminate) will be unblocked.
266
267 If there are no threads blocked in a "cond_wait" on the variable,
268 the signal is discarded. By always locking before signaling, you
269 can (with care), avoid signaling before another thread has entered
270 cond_wait().
271
272 "cond_signal" will normally generate a warning if you attempt to
273 use it on an unlocked variable. On the rare occasions where doing
274 this may be sensible, you can suppress the warning with:
275
276 { no warnings 'threads'; cond_signal($foo); }
277
278 cond_broadcast VARIABLE
279 The "cond_broadcast" function works similarly to "cond_signal".
280 "cond_broadcast", though, will unblock all the threads that are
281 blocked in a "cond_wait" on the locked variable, rather than only
282 one.
283
285 threads::shared exports a version of bless() that works on shared
286 objects such that blessings propagate across threads.
287
288 # Create a shared 'Foo' object
289 my $foo :shared = shared_clone({});
290 bless($foo, 'Foo');
291
292 # Create a shared 'Bar' object
293 my $bar :shared = shared_clone({});
294 bless($bar, 'Bar');
295
296 # Put 'bar' inside 'foo'
297 $foo->{'bar'} = $bar;
298
299 # Rebless the objects via a thread
300 threads->create(sub {
301 # Rebless the outer object
302 bless($foo, 'Yin');
303
304 # Cannot directly rebless the inner object
305 #bless($foo->{'bar'}, 'Yang');
306
307 # Retrieve and rebless the inner object
308 my $obj = $foo->{'bar'};
309 bless($obj, 'Yang');
310 $foo->{'bar'} = $obj;
311
312 })->join();
313
314 print(ref($foo), "\n"); # Prints 'Yin'
315 print(ref($foo->{'bar'}), "\n"); # Prints 'Yang'
316 print(ref($bar), "\n"); # Also prints 'Yang'
317
319 threads::shared is designed to disable itself silently if threads are
320 not available. This allows you to write modules and packages that can
321 be used in both threaded and non-threaded applications.
322
323 If you want access to threads, you must "use threads" before you "use
324 threads::shared". threads will emit a warning if you use it after
325 threads::shared.
326
328 When "share" is used on arrays, hashes, array refs or hash refs, any
329 data they contain will be lost.
330
331 my @arr = qw(foo bar baz);
332 share(@arr);
333 # @arr is now empty (i.e., == ());
334
335 # Create a 'foo' object
336 my $foo = { 'data' => 99 };
337 bless($foo, 'foo');
338
339 # Share the object
340 share($foo); # Contents are now wiped out
341 print("ERROR: \$foo is empty\n")
342 if (! exists($foo->{'data'}));
343
344 Therefore, populate such variables after declaring them as shared.
345 (Scalar 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
348 been written to support sharing. For example, an object's destructor
349 may get called multiple times, once for each thread's scope exit.
350 Another danger is that the contents of hash-based objects will be lost
351 due to the above mentioned limitation. See examples/class.pl (in the
352 CPAN distribution of this module) for how to create a class that
353 supports object sharing.
354
355 Destructors may not be called on objects if those objects still exist
356 at global destruction time. If the destructors must be called, make
357 sure there are no circular references and that nothing is referencing
358 the objects, before the program ends.
359
360 Does not support "splice" on arrays. Does not support explicitly
361 changing array lengths via $#array -- use "push" and "pop" instead.
362
363 Taking references to the elements of shared arrays and hashes does not
364 autovivify the elements, and neither does slicing a shared array/hash
365 over non-existent indices/keys autovivify the elements.
366
367 "share()" allows you to "share($hashref->{key})" and
368 "share($arrayref->[idx])" without giving any error message. But the
369 "$hashref->{key}" or "$arrayref->[idx]" is not shared, causing the
370 error "lock can only be used on shared values" to occur when you
371 attempt to "lock($hashref->{key})" or "lock($arrayref->[idx])" in
372 another thread.
373
374 Using refaddr()) is unreliable for testing whether or not two shared
375 references are equivalent (e.g., when testing for circular references).
376 Use is_shared(), instead:
377
378 use threads;
379 use threads::shared;
380 use Scalar::Util qw(refaddr);
381
382 # If ref is shared, use threads::shared's internal ID.
383 # Otherwise, use refaddr().
384 my $addr1 = is_shared($ref1) || refaddr($ref1);
385 my $addr2 = is_shared($ref2) || refaddr($ref2);
386
387 if ($addr1 == $addr2) {
388 # The refs are equivalent
389 }
390
391 each() does not work properly on shared references embedded in shared
392 structures. For example:
393
394 my %foo :shared;
395 $foo{'bar'} = shared_clone({'a'=>'x', 'b'=>'y', 'c'=>'z'});
396
397 while (my ($key, $val) = each(%{$foo{'bar'}})) {
398 ...
399 }
400
401 Either of the following will work instead:
402
403 my $ref = $foo{'bar'};
404 while (my ($key, $val) = each(%{$ref})) {
405 ...
406 }
407
408 foreach my $key (keys(%{$foo{'bar'}})) {
409 my $val = $foo{'bar'}{$key};
410 ...
411 }
412
413 This module supports dual-valued variables created using dualvar() from
414 Scalar::Util). However, while $! acts like a dualvar, it is
415 implemented as a tied SV. To propagate its value, use the follow
416 construct, if needed:
417
418 my $errno :shared = dualvar($!,$!);
419
420 View existing bug reports at, and submit any new bugs, problems,
421 patches, etc. to:
422 <http://rt.cpan.org/Public/Dist/Display.html?Name=threads-shared>
423
425 threads::shared Discussion Forum on CPAN:
426 <http://www.cpanforum.com/dist/threads-shared>
427
428 threads, perlthrtut
429
430 <http://www.perl.com/pub/a/2002/06/11/threads.html> and
431 <http://www.perl.com/pub/a/2002/09/04/threads.html>
432
433 Perl threads mailing list: <http://lists.perl.org/list/ithreads.html>
434
436 Artur Bergman <sky AT crucially DOT net>
437
438 Documentation borrowed from the old Thread.pm.
439
440 CPAN version produced by Jerry D. Hedden <jdhedden AT cpan DOT org>.
441
443 threads::shared is released under the same license as Perl.
444
445
446
447perl v5.16.3 2013-01-14 threads::shared(3)