@@ -540,8 +540,6 @@ Beyond that there are no further facilities for synchronization or resource
540
540
sharing which is largely why it should be emphasised that threads are unlikely
541
541
to be useful directly in user code.
542
542
543
-
544
-
545
543
= head2 Schedulers
546
544
547
545
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
615
613
is that C < cue > on this scheduler will block until the code finishes
616
614
execution, limiting its utility to certain special cases such as testing.
617
615
618
- = begin comment
619
-
620
- I couldn't think of a non-contrived but succinct example for a use-case
616
+ = head2 Locks
621
617
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.
623
624
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:
624
629
625
- = begin comment
630
+ my $lock = Lock.new;
626
631
627
- = head3 tap
632
+ my $a = 0;
628
633
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
+ }
632
643
633
- = end comment
644
+ say $a; # 10
634
645
646
+ C < protect > returns whatever the code block returns.
635
647
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.
636
650
637
651
= end pod
0 commit comments