Skip to content

Commit

Permalink
Expand Lock.protect docs
Browse files Browse the repository at this point in the history
To explain the lock must be instantiated outside the threaded area
  • Loading branch information
zoffixznet committed Jun 2, 2017
1 parent d3d3fa3 commit f98e28f
Showing 1 changed file with 30 additions and 2 deletions.
32 changes: 30 additions & 2 deletions doc/Type/Lock.pod6
Expand Up @@ -37,8 +37,36 @@ Defined as:
Runs C<&code> and makes sure it is only run in one thread at once.
my $l = Lock.new;
$l.protect({ #`( some unsafe operations here ) 1 + 1; });
Note that the L<Lock> itself needs to be created outside the portion
of the code that gets threaded and it needs to protect. In the first
example below, L<Lock> is first created and assigned to C<$lock>,
which is then used I<inside> the L<Promises|/type/Promise> to protect
the sensitive code. In the second example, a mistake is made, the
C<Lock> is created right inside the L<Promise>, so the code ends up
with a bunch of separate locks, created in a bunch of threads, and
thus they don't actually protect the code we want to protect.
# Right: $lock is instantiated outside the portion of the
# code that will get threaded and be in need of protection
my $lock = Lock.new;
await ^20 .map: {
start {
$lock.protect: {
print "Foo";
sleep rand;
say "Bar";
}
}
}
# !!! WRONG !!! Lock is created inside threaded area!
await ^20 .map: {
start {
Lock.new.protect: {
print "Foo"; sleep rand; say "Bar";
}
}
}
=head2 method lock
Expand Down

0 comments on commit f98e28f

Please sign in to comment.