Logo

Programming-Idioms

History of Idiom 33 > diff from v10 to v11

Edit summary for version 11 by :

Version 10

2015-09-05, 16:33:31

Version 11

2015-09-06, 16:12:50

Idiom #33 Atomically read and update variable

Assign variable x the new value f(x), making sure that no other thread may modify x between the read and the write.

Idiom #33 Atomically read and update variable

Assign variable x the new value f(x), making sure that no other thread may modify x between the read and the write.

Imports
use threads;
use threads::shared;
Imports
use threads;
use threads::shared;
Code
my $x :shared;
$x = 0;

sub my_task {
   my $id = shift;
   for (1 .. 5) {
      sleep 2*rand();
      { # lock scope
         lock($x);
         print "thread $id found $x\n";
         $x = $id;
         sleep 2*rand();
      }
   }
}

threads->create('my_task', $_) for 1 .. 3;
sleep 5 while threads->list(threads::running);
Code
my $x :shared;
$x = 0;

sub my_task {
   my $id = shift;
   for (1 .. 5) {
      sleep 2*rand();
      { # lock scope
         lock($x);
         print "thread $id found $x\n";
         $x = $id;
         sleep 2*rand();
      }
   }
}

threads->create('my_task', $_) for 1 .. 3;
sleep 5 while threads->list(threads::running);
Comments bubble
lock is lexically scoped. Delay outside the lock scope allows other threads a chance at changing $x.
Comments bubble
lock is lexically scoped. Delay outside the lock scope allows other threads a chance at changing $x.