Logo

Programming-Idioms

History of Idiom 33 > diff from v1 to v2

Edit summary for version 2 by :

Version 1

2015-05-06, 21:04:49

Version 2

2015-08-01, 01:54:19

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;
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.