Semaphore Reference
Control access to shared resources by multiple threads
What it is #
class Semaphore { }
Routines #
Signatures are reproduced from the documentation, including their declared return types. A routine listed here is part of the type's published interface; whether Raku++ implements it is a separate question, answered by the examples below.
method new #
method new( int $permits ) Initialize the semaphore with the number of permitted accesses. E.g. when set to 2, program threads can pass the acquire method twice until it blocks on the third time acquire is called.
method acquire #
method acquire() Acquire access. When other threads have called the method before and the number of permits are used up, the process blocks until threads passed before releases the semaphore.
method try_acquire #
method try_acquire(--> Bool) Same as acquire but will not block. Instead it returns True if access is permitted or False otherwise.
method release #
method release() Release the semaphore raising the number of permissions. Any blocked thread will get access after that.
Examples, run three ways #
Every example below comes from the official documentation, together with the output that documentation asserts. Each was then executed by Rakudo and by Raku++ when this page was built. Where the three agree, one result is shown; where they do not, all three are — because which of them is wrong is exactly the information worth having.
7 no-output
has Array $!printers; has Semaphore $!print-control;
Not executed: the documentation states no expected output for this example.
method BUILD( Int:D :$nbr-printers ) {
for ^$nbr-printers -> $pc {
$!printers[$pc] = { :name{"printer-$pc"} };
}Not executed: the documentation states no expected output for this example.
$!print-control .= new($nbr-printers); }
Not executed: the documentation states no expected output for this example.
method find-available-printer-and-print-it($job) { say "Is printed!"; }Not executed: the documentation states no expected output for this example.
method print( $print-job ) {
$!print-control.acquire;Not executed: the documentation states no expected output for this example.
self.find-available-printer-and-print-it($print-job);
Not executed: the documentation states no expected output for this example.
$!print-control.release; }
Not executed: the documentation states no expected output for this example.