in reply to Sharing in fork
perl's threads are not like other language's threads; they operate much like processes in that they don't share variables. Here's a thread example:
See perthrtut for more info. Or see perlipc for other ideas.use strict; use warnings; use 5.010; use threads; use threads::shared; my $val :shared = 10; my $other_val = 'hello'; sub do_stuff { my $thr_id = shift; sleep int(rand 3); $other_val .= ' world'; { lock $val; #other threads cannot access $val until after #this block exits say "thread$thr_id sees:"; say "\t\$val = $val"; say "\t\$other_val = $other_val"; $val += 2; } } for (1 .. 10) { threads->new(\&do_stuff, $_); } for my $thr ( threads->list() ) { $thr->join(); } --output:-- thread4 sees: $val = 10 $other_val = hello world thread6 sees: $val = 12 $other_val = hello world thread1 sees: $val = 14 $other_val = hello world thread3 sees: $val = 16 $other_val = hello world thread5 sees: $val = 18 $other_val = hello world thread8 sees: $val = 20 $other_val = hello world thread10 sees: $val = 22 $other_val = hello world thread2 sees: $val = 24 $other_val = hello world thread7 sees: $val = 26 $other_val = hello world thread9 sees: $val = 28 $other_val = hello world
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Sharing in fork
by ajeet@perl (Acolyte) on Mar 23, 2010 at 10:04 UTC | |
by Corion (Patriarch) on Mar 23, 2010 at 10:09 UTC |