Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • Perl

Idiom #33 Atomically read and update variable

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

use threads;
use threads::shared;
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);

lock is lexically scoped. Delay outside the lock scope allows other threads a chance at changing $x.
(def x (atom 0))
(def f inc)
(swap! x f)

New implementation...
< >
programming-idioms.org