Skip to content

Instantly share code, notes, and snippets.

@dakkar
Last active June 21, 2023 13:05
Show Gist options
  • Save dakkar/d1a44ad8febfdbd0fbdb5d7cd3994d4e to your computer and use it in GitHub Desktop.
Save dakkar/d1a44ad8febfdbd0fbdb5d7cd3994d4e to your computer and use it in GitHub Desktop.
locked-by raku trait
use v6.d;
use lib '.';
use LockedBy;
class Counter {
has Lock $.one = Lock.new;
has Int $counter = 0;
# access the lock as private attribute
method increment() is locked-by<$!one> { ++$!counter }
# access the lock as public method
method get() is locked-by<one> { $!counter }
}
my $c = Counter.new;
$c.increment();
say $c.get;
use v6.d;
multi sub trait_mod:<is>(Method $r, Str:D :$locked-by!) is export {
$r.wrap(method (|capture) {
my $lock := ($locked-by ~~ /^ '$!' /)
?? self.^attribute_table(){$locked-by}.get_value(self)
!! self."$locked-by"();
my &next := nextcallee;
my $result;
$lock.protect(
-> { $result := next(self, |capture) }
);
return $result;
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment