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.60
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 (see Scalar::Util). 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 cond_broadcast() called on unlocked variable
329 cond_signal() called on unlocked variable
330 See "cond_signal VARIABLE", above.
331
333 When "share" is used on arrays, hashes, array refs or hash refs, any
334 data they contain will be lost.
335
336 my @arr = qw(foo bar baz);
337 share(@arr);
338 # @arr is now empty (i.e., == ());
339
340 # Create a 'foo' object
341 my $foo = { 'data' => 99 };
342 bless($foo, 'foo');
343
344 # Share the object
345 share($foo); # Contents are now wiped out
346 print("ERROR: \$foo is empty\n")
347 if (! exists($foo->{'data'}));
348
349 Therefore, populate such variables after declaring them as shared.
350 (Scalar and scalar refs are not affected by this problem.)
351
352 Blessing a shared item after it has been nested in another shared item
353 does not propagate the blessing to the shared reference:
354
355 my $foo = &share({});
356 my $bar = &share({});
357 $bar->{foo} = $foo;
358 bless($foo, 'baz'); # $foo is now of class 'baz',
359 # but $bar->{foo} is unblessed.
360
361 Therefore, you should bless objects before sharing them.
362
363 It is often not wise to share an object unless the class itself has
364 been written to support sharing. For example, a shared object's
365 destructor may get called multiple times, once for each thread's scope
366 exit, or may not get called at all if it is embedded inside another
367 shared object. Another issue is that the contents of hash-based
368 objects will be lost due to the above mentioned limitation. See
369 examples/class.pl (in the CPAN distribution of this module) for how to
370 create a class that supports object sharing.
371
372 Destructors may not be called on objects if those objects still exist
373 at global destruction time. If the destructors must be called, make
374 sure there are no circular references and that nothing is referencing
375 the objects before the program ends.
376
377 Does not support "splice" on arrays. Does not support explicitly
378 changing array lengths via $#array -- use "push" and "pop" instead.
379
380 Taking references to the elements of shared arrays and hashes does not
381 autovivify the elements, and neither does slicing a shared array/hash
382 over non-existent indices/keys autovivify the elements.
383
384 "share()" allows you to "share($hashref->{key})" and
385 "share($arrayref->[idx])" without giving any error message. But the
386 "$hashref->{key}" or "$arrayref->[idx]" is not shared, causing the
387 error "lock can only be used on shared values" to occur when you
388 attempt to "lock($hashref->{key})" or "lock($arrayref->[idx])" in
389 another thread.
390
391 Using "refaddr()" is unreliable for testing whether or not two shared
392 references are equivalent (e.g., when testing for circular references).
393 Use is_shared(), instead:
394
395 use threads;
396 use threads::shared;
397 use Scalar::Util qw(refaddr);
398
399 # If ref is shared, use threads::shared's internal ID.
400 # Otherwise, use refaddr().
401 my $addr1 = is_shared($ref1) || refaddr($ref1);
402 my $addr2 = is_shared($ref2) || refaddr($ref2);
403
404 if ($addr1 == $addr2) {
405 # The refs are equivalent
406 }
407
408 each() does not work properly on shared references embedded in shared
409 structures. For example:
410
411 my %foo :shared;
412 $foo{'bar'} = shared_clone({'a'=>'x', 'b'=>'y', 'c'=>'z'});
413
414 while (my ($key, $val) = each(%{$foo{'bar'}})) {
415 ...
416 }
417
418 Either of the following will work instead:
419
420 my $ref = $foo{'bar'};
421 while (my ($key, $val) = each(%{$ref})) {
422 ...
423 }
424
425 foreach my $key (keys(%{$foo{'bar'}})) {
426 my $val = $foo{'bar'}{$key};
427 ...
428 }
429
430 This module supports dual-valued variables created using "dualvar()"
431 from Scalar::Util. However, while $! acts like a dualvar, it is
432 implemented as a tied SV. To propagate its value, use the follow
433 construct, if needed:
434
435 my $errno :shared = dualvar($!,$!);
436
437 View existing bug reports at, and submit any new bugs, problems,
438 patches, etc. to:
439 <http://rt.cpan.org/Public/Dist/Display.html?Name=threads-shared>
440
442 threads::shared on MetaCPAN:
443 <https://metacpan.org/release/threads-shared>
444
445 Code repository for CPAN distribution:
446 <https://github.com/Dual-Life/threads-shared>
447
448 threads, perlthrtut
449
450 <http://www.perl.com/pub/a/2002/06/11/threads.html> and
451 <http://www.perl.com/pub/a/2002/09/04/threads.html>
452
453 Perl threads mailing list: <http://lists.perl.org/list/ithreads.html>
454
455 Sample code in the examples directory of this distribution on CPAN.
456
458 Artur Bergman <sky AT crucially DOT net>
459
460 Documentation borrowed from the old Thread.pm.
461
462 CPAN version produced by Jerry D. Hedden <jdhedden AT cpan DOT org>.
463
465 threads::shared is released under the same license as Perl.
466
467
468
469perl v5.30.1 2020-01-30 threads::shared(3)