class Semaphore

Table of Contents

Protect your shared code, data or device access using semaphores. An example is a printer manager managing a pool of printers without the need of storing print jobs when all printers are occupied. The next job is just blocked until a printer becomes available.

classprint-manager{

hasArray$!printers;

hasSemaphore$!print-control;

methodBUILD( Int:D:$nbr-printers ) {

for^$nbr-printers->$pc{

$!printers[$pc] ={:name{"printer-$pc"}};

}

$!print-control.=new($nbr-printers);

}

methodfind-available-printer-and-print-it($job) {say"Is printed!"; }

methodprint( $print-job ) {

$!print-control.acquire;

self.find-available-printer-and-print-it($print-job);

$!print-control.release;

}

}

Another example is a protection around code updating sensitive data. In such a case the semaphore is typically initialized to 1.

It is important to have a release on every exit of your program! While this is obvious, it is easy to fall in traps such as throwing an exception caused by some event. When the program dies there is no problem. When the exception is caught your program might eventually come back to the acquire method and will hang indefinitely.