Skip to content

Commit 935985d

Browse files
committed
Add section for Lock
1 parent 343fca6 commit 935985d

File tree

1 file changed

+26
-12
lines changed

1 file changed

+26
-12
lines changed

lib/Language/concurrency.pod

Lines changed: 26 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -540,8 +540,6 @@ Beyond that there are no further facilities for synchronization or resource
540540
sharing which is largely why it should be emphasised that threads are unlikely
541541
to be useful directly in user code.
542542
543-
544-
545543
=head2 Schedulers
546544
547545
The next level of the concurrency API is that supplied by classes that
@@ -615,23 +613,39 @@ schedule code to be run straight away on the current thread. The implication
615613
is that C<cue> on this scheduler will block until the code finishes
616614
execution, limiting its utility to certain special cases such as testing.
617615
618-
=begin comment
619-
620-
I couldn't think of a non-contrived but succinct example for a use-case
616+
=head2 Locks
621617
622-
=end comment
618+
The class L<Lock> provides the low level mechanism that protects
619+
shared data in a concurrent environment and is thus key to supporting
620+
thread-safety in the high level API, this is sometimes known as a
621+
"Mutex" in other programming languages. Because the higher level classes
622+
(L<Promise>, L<Supply> andL<Channel>,) use a L<Lock> where required it
623+
is unlikey that user code will need to use a L<Lock> directly.
623624
625+
The primary interface to L<Lock> is the method
626+
L<protect|/type/Lock#method_protect> which ensures that a block of code
627+
(commonly called a "critical section",) is only executed in one thread
628+
at a time:
624629
625-
=begin comment
630+
my $lock = Lock.new;
626631
627-
=head3 tap
632+
my $a = 0;
628633
629-
=head3 emit
630-
631-
=head2 channels
634+
await (^10).map: {
635+
start {
636+
$lock.protect({
637+
my $r = rand;
638+
sleep $r;
639+
$a++;
640+
});
641+
}
642+
}
632643
633-
=end comment
644+
say $a; # 10
634645
646+
C<protect> returns whatever the code block returns.
635647
648+
Because C<protect> will block any threads that are waiting to execute
649+
the critical section the code should be as quick as possible.
636650
637651
=end pod

0 commit comments

Comments
 (0)