| Refresh | Home EGTry.com

define perl variable (scalar, array or hash) that can be accessed or modified by different threads

perl code example -- two threads add up the shared $total

use threads;
use threads::shared;

my $total :shared=0;

my $t1=threads->create(\&add, "t1");
my $t2=threads->create(\&add, "t2");


print "now the total is: $total\n";

sub add {
  my $name=shift;
  for(my $i=0; $i<10; $i++) {
    print "$name before total=$total\n";
    print "$name after total=$total\n\n";


t1 before total=0
t1 after total=1

t1 before total=2
t1 after total=3

t1 before total=4
t1 after total=5

t1 before total=6
t1 after total=7

t1 before total=8
t1 after total=9

t1 before total=10
t1 after total=11

t1 before total=12
t1 after total=13

t1 before total=14
t1 after total=15

t1 before total=16
t1 after total=17

t1 before total=18
t1 after total=19

t2 before total=1
t2 after total=2

t2 before total=3
t2 after total=4

t2 before total=5
t2 after total=6

t2 before total=7
t2 after total=8

t2 before total=9
t2 after total=10

t2 before total=11
t2 after total=12

t2 before total=13
t2 after total=14

t2 before total=15
t2 after total=16

t2 before total=17
t2 after total=18

t2 before total=19
t2 after total=20

now the total is: 20