Metered concurrency: Difference between revisions

From Rosetta Code
Content added Content deleted
mNo edit summary
Line 1: Line 1:
{{task}}
[http://jazzyjoe.ifrance.com/gay-annunci/ gay annunci] [http://belikan.ifrance.com/library/galesburg.htm galesburg] [http://shotlandetz.ifrance.com/blog/michael-vieth/ michael vieth] [http://chrystiala.ifrance.com/library/vasco-in.htm vasco in tuor] [http://shotlandetz.ifrance.com/blog/frigorifero-rex/ frigorifero rex rc200] [http://shotlandetz.ifrance.com/blog/vostro-figlio/ vostro figlio e fratello] [http://animaetrix00.ifrance.com/content/like-a/ like a virgin] [http://belikan.ifrance.com/library/renee-zellweger.htm renee zellweger] [http://pouringsunny.ifrance.com/description/maysa-leak/ maysa leak] [http://shmarodral.ifrance.com/text/syberia.htm syberia 2] [http://shmarodral.ifrance.com/text/caldereria.htm caldereria] [http://pouringsunny.ifrance.com/description/sony-mavica/ sony mavica mvc fd92] [http://listsobacka.ifrance.com/small/cordless-mx.htm cordless mx] [http://lethalga.ifrance.com/topic/gocce-dal/ gocce dal cielo] [http://listsobacka.ifrance.com/small/capo-di.htm capo di banda] [http://chrystiala.ifrance.com/library/i-vampiri.htm i vampiri dello spazio] [http://feelosof.ifrance.com/description/il-simbolo/ il simbolo del sesso] [http://thecakeblog.ifrance.com/articles/amori-rai/ amori rai it] [http://infunt.ifrance.com/articles/infedeli/ infedeli] [http://jazzyjoe.ifrance.com/goliath-e/ goliath e la schiava ribelle] [http://liubash.ifrance.com/new/sun-bitches.htm sun bitches] [http://feelosof.ifrance.com/description/kilie-minogue/ kilie minogue video your eyes] [http://eccoblackfin.ifrance.com/html/maschi-con.htm maschi con maschi nudi] [http://jojorock.ifrance.com/articles/ingrid-milord/ ingrid milord free] [http://lethalga.ifrance.com/topic/crediveneto/ crediveneto] [http://pouringsunny.ifrance.com/description/giada-isola/ giada isola dei famosi nuda] [http://shotlandetz.ifrance.com/blog/mercedes-a/ mercedes a 150 classic] [http://jene7777777.ifrance.com/new/prodotti-gatti.htm prodotti gatti] [http://belikan.ifrance.com/library/xerox-com.htm xerox com ar] [http://belikan.ifrance.com/library/pryda.htm pryda] [http://infunt.ifrance.com/articles/powerbook-/ powerbook 15 superdrive] [http://firejedi.ifrance.com/new/costa-rei/ costa rei vacanze] [http://shmarodral.ifrance.com/text/new-keys.htm new keys arabesque] [http://feelosof.ifrance.com/description/accessorio-macchina/ accessorio macchina] [http://thecakeblog.ifrance.com/articles/nederlandse-zenders/ nederlandse zenders] [http://firejedi.ifrance.com/new/euro-dance/ euro dance 1] [http://chrystiala.ifrance.com/library/shuttle-accessori.htm shuttle accessori] [http://firejedi.ifrance.com/new/cicc/ cicc] [http://infunt.ifrance.com/articles/www-googlee/ www googlee it] [http://jojorock.ifrance.com/articles/fun-magic/ fun magic 1 4] [http://animaetrix00.ifrance.com/content/fax/ fax] [http://feelosof.ifrance.com/description/crime-de/ crime de sylvestre bonnard le] [http://animaetrix00.ifrance.com/content/arbour/ arbour 3 06] [http://eccoblackfin.ifrance.com/html/lavatrice-indesit.htm lavatrice indesit] [http://shmarodral.ifrance.com/text/stampante-hp.htm stampante hp 3745] [http://jojorock.ifrance.com/articles/nvidia-fx/ nvidia fx1400 128 mb] [http://ohmygoshalix.ifrance.com/blog/foza-venite.htm foza venite gente] [http://eccoblackfin.ifrance.com/html/foto-di.htm foto di animali delfini] [http://jojorock.ifrance.com/articles/haiducii-gabry/ haiducii gabry dragostea] [http://feelosof.ifrance.com/description/hector-y/ hector y tito videoclips] [http://shotlandetz.ifrance.com/blog/ryan-cabrera/ ryan cabrera take all away] [http://listsobacka.ifrance.com/small/video-pono.htm video pono gratis] [http://chrystiala.ifrance.com/library/frigorifero-combinato.htm frigorifero combinato] [http://listsobacka.ifrance.com/small/fonderie-acciaierie.htm fonderie acciaierie] [http://feelosof.ifrance.com/description/michael-jackson/ michael jackson invincible] [http://liubash.ifrance.com/new/canzone-ciapa.htm canzone ciapa la galeina] [http://cikumuffin.ifrance.com/topic/terratec-grabster/ terratec grabster av 250] [http://infunt.ifrance.com/articles/accessorio-alcatel/ accessorio alcatel] [http://jojorock.ifrance.com/articles/gto-great/ gto great teacher onizuka disco 4] [http://thecakeblog.ifrance.com/articles/acer-altos/ acer altos] [http://feelosof.ifrance.com/description/opportunita-di/ opportunita di pace] [http://shotlandetz.ifrance.com/blog/adobe-creative/ adobe creative suite 1 6 premium] [http://jene7777777.ifrance.com/new/emma-dumas.htm emma dumas] [http://shmarodral.ifrance.com/text/sexo-latinas.htm sexo latinas] [http://animaetrix00.ifrance.com/content/abbigliamento-donna/ abbigliamento donna elegante] [http://listsobacka.ifrance.com/small/acropora.htm acropora] [http://shmarodral.ifrance.com/text/io-con.htm io con te non ci sto piu] [http://shotlandetz.ifrance.com/blog/dvd-rw/ dvd rw divx con hd lettori] [http://chrystiala.ifrance.com/library/hana-melonova.htm hana melonova] [http://seachildelf.ifrance.com/resources/ddr-/ ddr 400 mhz 512 mb] [http://liubash.ifrance.com/new/testo-sunrise.htm testo sunrise] [http://firejedi.ifrance.com/new/normativa-licenziamento/ normativa licenziamento] [http://listsobacka.ifrance.com/small/califfo.htm califfo] [http://thecakeblog.ifrance.com/articles/film-porno/ film porno barbara chiappini] [http://ohmygoshalix.ifrance.com/blog/la-historia.htm la historia del carro] [http://emrinalexander.ifrance.com/styles/snoop-dogg.htm snoop dogg feat pharrell beaut] [http://belikan.ifrance.com/library/quintet.htm quintet] [http://thecakeblog.ifrance.com/articles/gomma-e/ gomma e materie plastiche] [http://beatpoetsa.ifrance.com/description/campeggio-ischia.htm campeggio ischia] [http://jazzyjoe.ifrance.com/ghiacciolo/ ghiacciolo] [http://emrinalexander.ifrance.com/styles/un-altro.htm un altro ballo mp3] [http://listsobacka.ifrance.com/small/sigla-spot.htm sigla spot] [http://infunt.ifrance.com/articles/the-blood/ the blood diamond] [http://lethalga.ifrance.com/topic/notebook-lock/ notebook lock] [http://emrinalexander.ifrance.com/styles/absit-iniuria.htm absit iniuria verbo] [http://cikumuffin.ifrance.com/topic/big-cyc/ big cyc] [http://emrinalexander.ifrance.com/styles/plasma-hyundai.htm plasma hyundai hqp421hr] [http://firejedi.ifrance.com/new/codec-nero/ codec nero mpeg2] [http://beatpoetsa.ifrance.com/description/rode-helge.htm rode helge] [http://makkiesan.ifrance.com/seannateen.htm seannateen] [http://listsobacka.ifrance.com/small/campolongu.htm campolongu] [http://feelosof.ifrance.com/description/monitor-cruscotto/ monitor cruscotto] [http://animaetrix00.ifrance.com/content/limone-del/ limone del garda] [http://pouringsunny.ifrance.com/description/remos/ remos] [http://emrinalexander.ifrance.com/styles/ladro-e.htm ladro e gentiluomo] [http://jazzyjoe.ifrance.com/tragico-oriente/ tragico oriente] [http://jene7777777.ifrance.com/new/noe-we.htm noe we are free] [http://thecakeblog.ifrance.com/articles/km-bmw/ km0 bmw 120] [http://pouringsunny.ifrance.com/description/umidita-risalita/ umidita risalita] [http://firejedi.ifrance.com/new/terapia-luce/ terapia luce] [http://shmarodral.ifrance.com/text/herceptin-iv.htm herceptin iv 1 fl 150 mg] [http://jazzyjoe.ifrance.com/blu-chat/ blu chat] [http://jazzyjoe.ifrance.com/eizo-monitor/ eizo monitor cg21] [http://shmarodral.ifrance.com/text/hp-nx.htm hp nx6110 512 centrino] [http://infunt.ifrance.com/articles/tom-hanks/ tom hanks] [http://thecakeblog.ifrance.com/articles/violadores-de/ violadores de la selva] [http://pouringsunny.ifrance.com/description/satyricom/ satyricom] [http://jene7777777.ifrance.com/new/nonne-ose.htm nonne ose] [http://firejedi.ifrance.com/new/i-lupi/ i lupi attaccano in branco] [http://jojorock.ifrance.com/articles/case-di/ case di riposo private] [http://ohmygoshalix.ifrance.com/blog/www-hotel.htm www hotel] [http://emrinalexander.ifrance.com/styles/de-ce.htm de ce mea minti] [http://eccoblackfin.ifrance.com/html/shopping-egno.htm shopping egno] [http://jene7777777.ifrance.com/new/aparasphenodon.htm aparasphenodon] [http://firejedi.ifrance.com/new/musica-en/ musica en el renacimiento] [http://thecakeblog.ifrance.com/articles/tv-lcd/ tv lcd 20 keymat] [http://eccoblackfin.ifrance.com/html/flevoland.htm flevoland] [http://shmarodral.ifrance.com/text/sony-dcrpce.htm sony dcrpc103e] [http://listsobacka.ifrance.com/small/melissa-vieni.htm melissa vieni a cantare] [http://liubash.ifrance.com/new/md-adsl.htm md4100 adsl modemrouter] [http://liubash.ifrance.com/new/fotocamera-.htm fotocamera 2 0 pixel] [http://eccoblackfin.ifrance.com/html/cv-f.htm cv 150f] [http://belikan.ifrance.com/library/verbatim-cdr.htm verbatim cdr 80 min 700 mb 52x] [http://liubash.ifrance.com/new/anelli-oro.htm anelli oro bianco] [http://lethalga.ifrance.com/topic/www-mirabilandia/ www mirabilandia it] [http://shotlandetz.ifrance.com/blog/hp-qa/ hp q7971a] [http://firejedi.ifrance.com/new/piacenza-bsx/ piacenza bsx] [http://belikan.ifrance.com/library/mocassini-prada.htm mocassini prada] [http://jene7777777.ifrance.com/new/stampanti-laser.htm stampanti laser hp 3500] [http://firejedi.ifrance.com/new/traduzione-di/ traduzione di the power of love di celin] [http://shmarodral.ifrance.com/text/racchetta-beach.htm racchetta beach tennis king] [http://infunt.ifrance.com/articles/www-pitneybowes/ www pitneybowes com] [http://jojorock.ifrance.com/articles/tiziano-ferro/ tiziano ferro basi] [http://chrystiala.ifrance.com/library/www-pesci.htm www pesci di mare it] [http://seachildelf.ifrance.com/resources/distributore-philips/ distributore philips italia] [http://pouringsunny.ifrance.com/description/guasti-clio/ guasti clio] [http://lethalga.ifrance.com/topic/la-bella/ la bella antonia] [http://jene7777777.ifrance.com/new/sanyo-fotocamere.htm sanyo fotocamere digitali] [http://eccoblackfin.ifrance.com/html/zalman-vfcu.htm zalman vf700cu] [http://shmarodral.ifrance.com/text/docking-station.htm docking station serie m] [http://pouringsunny.ifrance.com/description/rivoluzione-russa/ rivoluzione russa] [http://shmarodral.ifrance.com/text/hello-lionel.htm hello lionel richie] [http://emrinalexander.ifrance.com/styles/nuova-honda.htm nuova honda benzina auto nuove] [http://shmarodral.ifrance.com/text/lo-zingaro.htm lo zingaro] [http://firejedi.ifrance.com/new/www-ministero/ www ministero istruzione padova] [http://shotlandetz.ifrance.com/blog/le-arene/ le arene a catania] [http://makkiesan.ifrance.com/l-acqua.htm l acqua e poca] [http://eccoblackfin.ifrance.com/html/hard-disk.htm hard disk maxtor 160 gb] [http://chrystiala.ifrance.com/library/racconti-erotici.htm racconti erotici cani] [http://infunt.ifrance.com/articles/acer-lcd/ acer lcd 15] [http://emrinalexander.ifrance.com/styles/slim-ps.htm slim ps2] [http://jene7777777.ifrance.com/new/epox-amd.htm epox amd 939] [http://feelosof.ifrance.com/description/il-segno/ il segno di robin hood] [http://makkiesan.ifrance.com/se-qualcuno.htm se qualcuno deve morire] [http://animaetrix00.ifrance.com/content/banni/ banni] [http://shmarodral.ifrance.com/text/s-pentax.htm s45 pentax] [http://jazzyjoe.ifrance.com/toto-cutugno/ toto cutugno canzioni] [http://thecakeblog.ifrance.com/articles/calendario-azzurre/ calendario azzurre] [http://jene7777777.ifrance.com/new/cappa.htm cappa 80] [http://eccoblackfin.ifrance.com/html/canon-.htm canon powershot pro 1] [http://emrinalexander.ifrance.com/styles/resident-evil.htm resident evil main title] [http://liubash.ifrance.com/new/giacche-diesel.htm giacche diesel] [http://jojorock.ifrance.com/articles/gio-di/ gio di tonno] [http://makkiesan.ifrance.com/imetec-dolcevita.htm imetec dolcevita] [http://liubash.ifrance.com/new/monitor-lcd.htm monitor lcd sharp] [http://eccoblackfin.ifrance.com/html/lacie-gb.htm lacie 500gb] [http://lethalga.ifrance.com/topic/videos-de/ videos de hombres desnudos] [http://shotlandetz.ifrance.com/blog/gigi-d/ gigi d alessio testi] [http://jazzyjoe.ifrance.com/auto-noleggio/ auto noleggio orbetello] [http://chrystiala.ifrance.com/library/pastificio-la.htm pastificio la ginestra] [http://chrystiala.ifrance.com/library/kao-the.htm kao the kangaroo] [http://shotlandetz.ifrance.com/blog/offerta-montagna/ offerta montagna] [http://seachildelf.ifrance.com/resources/asus-anx/ asus a7n8x x] [http://lethalga.ifrance.com/topic/latte-ei/ latte ei suoi derivati] [http://feelosof.ifrance.com/description/grupo-exterminador/ grupo exterminador com] [http://jojorock.ifrance.com/articles/chicco-de/ chicco de matteo] [http://jojorock.ifrance.com/articles/mahshar-music/ mahshar music] [http://firejedi.ifrance.com/new/felicity-huffman/ felicity huffman] [http://jojorock.ifrance.com/articles/red-castle/ red castle] [http://eccoblackfin.ifrance.com/html/delfines.htm delfines] [http://ohmygoshalix.ifrance.com/blog/nervatura.htm nervatura] [http://chrystiala.ifrance.com/library/vendita-stampante.htm vendita stampante laser] [http://belikan.ifrance.com/library/blaupunkt-casablanca.htm blaupunkt casablanca mp54] [http://seachildelf.ifrance.com/resources/you-can/ you can leave tour hat on] [http://jojorock.ifrance.com/articles/guanti-pesistica/ guanti pesistica] [http://seachildelf.ifrance.com/resources/concorso-regione/ concorso regione salerno] [http://firejedi.ifrance.com/new/rs-mmc/ rs mmc 512 dv nokia 6680] [http://makkiesan.ifrance.com/scarica-suonerie.htm scarica suonerie senza costo] [http://animaetrix00.ifrance.com/content/jamelia-davis/ jamelia davis] [http://firejedi.ifrance.com/new/aspidogaster/ aspidogaster] [http://pouringsunny.ifrance.com/description/gruppi-islamici/ gruppi islamici] [http://beatpoetsa.ifrance.com/description/angel-killer.htm angel killer iii] [http://cikumuffin.ifrance.com/topic/corte-isolani/ corte isolani legno] [http://liubash.ifrance.com/new/telecel-bolivia.htm telecel bolivia] [http://jene7777777.ifrance.com/new/gabriel-garko.htm gabriel garko] [http://eccoblackfin.ifrance.com/html/fazio-wines.htm fazio wines] [http://liubash.ifrance.com/new/fot-gay.htm fot gay gratis] [http://animaetrix00.ifrance.com/content/indirizzi-parrocchie/ indirizzi parrocchie] [http://pouringsunny.ifrance.com/description/san-fiume/ san (fiume)] [http://jojorock.ifrance.com/articles/mutuo-agevolato/ mutuo agevolato] {{task}}


The goal of this task is to create a [http://en.wikipedia.org/wiki/Counting_semaphore counting semaphore] used to control the execution of a set of concurrent units. This task intends to demonstrate coordination of active concurrent units through the use of a passive concurrent unit. The operations for a counting semaphore are ''acquire'', ''release'', and ''count''. Each active concurrent unit should attempt to acquire the counting semaphore before executing its assigned duties. In this case the active concurrent unit should report that it has acquired the semaphore. It should sleep for 2 seconds and then release the semaphore.
The goal of this task is to create a [http://en.wikipedia.org/wiki/Counting_semaphore counting semaphore] used to control the execution of a set of concurrent units. This task intends to demonstrate coordination of active concurrent units through the use of a passive concurrent unit. The operations for a counting semaphore are ''acquire'', ''release'', and ''count''. Each active concurrent unit should attempt to acquire the counting semaphore before executing its assigned duties. In this case the active concurrent unit should report that it has acquired the semaphore. It should sleep for 2 seconds and then release the semaphore.
Line 32: Line 32:
entry Acquire when Lock_Count < Max is
entry Acquire when Lock_Count < Max is
begin
begin
Lock_Count := Lock_Count 1;
Lock_Count := Lock_Count + 1;
end Acquire;
end Acquire;
Line 79: Line 79:
Sleep_Time := Sleep;
Sleep_Time := Sleep;
end Start;
end Start;
--Acquire the lock. The task wil
--Acquire the lock. The task will suspend until the Acquire call completes
2000
l suspend until the Acquire call completes
Lock.Acquire;
Lock.Acquire;
Put_Line("Task #"
Put_Line("Task #" & Positive'Image(My_Id) & " acquired the lock.");
-- Suspend the task for Sleep_Time seconds
delay Sleep_Time;
-- Release the lock. Release is unconditional and happens without suspension
Lock.Release;
end Worker;
-- Create an array of 5 Workers
type Staff is array(Positive range 1..5) of Worker;
Crew : Staff;
begin
for I in Crew'range loop
Crew(I).Start(2.0, I);
end loop;
end Semaphores_Main;

==[[E]]==
[[Category:E]]

This semaphore slightly differs from the task description; the release operation is not on the semaphore itself but given out with each acquisition, and cannot be invoked too many times.

def makeSemaphore(maximum :(int > 0)) {
var current := 0
def waiters := <elib:vat.makeQueue>()
def notify() {
while (current < maximum && waiters.hasMoreElements()) {
current += 1
waiters.optDequeue().resolve(def released)
when (released) -> {
current -= 1
notify()
}
}
}
def semaphore {
to acquire() {
waiters.enqueue(def response)
notify()
return response
}
to count() { return current }
}
return semaphore
}
def work(label, interval, semaphore, timer, println) {
when (def releaser := semaphore <- acquire()) -> {
println(`$label: I have acquired the lock.`)
releaser.resolve(
timer.whenPast(timer.now() + interval, fn {
println(`$label: I will have released the lock.`)
})
)
}
}
def semaphore := makeSemaphore(3)
for i in 1..5 {
work(i, 2000, semaphore, timer, println)
}

==[[Java]]==
[[Category:Java]]
public class CountingSemaphore
{
private int lockCount = 0;
private int maxCount;
CountingSemaphore(int Max)
{
maxCount = Max;
}
public synchronized void acquire() throws InterruptedException
{
while( lockCount >= maxCount)
{
wait();
}
lockCount++;
}
public synchronized void release()
{
if (lockCount > 0)
{
lockCount--;
notifyAll();
}
}
public synchronized int getCount()
{
return lockCount;
}
}

public class Worker extends Thread
{
private CountingSemaphore lock;
private int id;
Worker(CountingSemaphore coordinator, int num)
{
lock = coordinator;
id = num;
}
Worker()
{
}
public void run()
{
try
{
lock.acquire();
System.out.println("Worker " + id + " has acquired the lock.");
sleep(2000);
}
catch (InterruptedException e)
{
}
finally
{
lock.release();
}
}
public static void main(String[] args)
{
CountingSemaphore lock = new CountingSemaphore(3);
Worker crew[];
crew = new Worker[5];
for (int i = 0; i < 5; i++)
{
crew[i] = new Worker(lock, i);
crew[i].start();
}
}
}

==[[Perl]]==
[[Category:Perl]]
See [http://search.cpan.org/dist/Coro/Coro/Semaphore.pm Coro::Semaphore].

Revision as of 19:12, 10 September 2007

Task
Metered concurrency
You are encouraged to solve this task according to the task description, using any language you may know.

The goal of this task is to create a counting semaphore used to control the execution of a set of concurrent units. This task intends to demonstrate coordination of active concurrent units through the use of a passive concurrent unit. The operations for a counting semaphore are acquire, release, and count. Each active concurrent unit should attempt to acquire the counting semaphore before executing its assigned duties. In this case the active concurrent unit should report that it has acquired the semaphore. It should sleep for 2 seconds and then release the semaphore.

Ada

Compiler: GNAT GPL 2006

The interface for the counting semaphore is defined in an Ada package specification:

package Semaphores is
   protected type Counting_Semaphore(Max : Positive) is
      entry Acquire;
      procedure Release;
      function Count return Natural;
   private
      Lock_Count : Natural := 0;
   end Counting_Semaphore;
end Semaphores;

The Acquire entry has a condition associated with it. A task can only execute the Acquire entry when Lock_Count is less than Max. This is the key to making this structure behave as a counting semaphore. This condition, and all the other aspects of Counting_Semaphore are contained in the package body.

package body Semaphores is

   ------------------------
   -- Counting_Semaphore --
   ------------------------ 

   protected body Counting_Semaphore is

      -------------
      -- Acquire --
      -------------

      entry Acquire when Lock_Count < Max is
      begin
         Lock_Count := Lock_Count + 1;
      end Acquire;

      -----------
      -- Count --
      -----------

      function Count return Natural is
      begin
         return Lock_Count;
      end Count;

      -------------
      -- Release --
      -------------

      procedure Release is
      begin
         if Lock_Count > 0 then
            Lock_Count := Lock_Count - 1;
         end if;
      end Release;

   end Counting_Semaphore;

end Semaphores;

We now need a set of tasks to properly call an instance of Counting_Semaphore.

with Semaphores;
with Ada.Text_Io; use Ada.Text_Io;

procedure Semaphores_Main is
   -- Create an instance of a Counting_Semaphore with Max set to 3
   Lock : Semaphores.Counting_Semaphore(3);

   -- Define a task type to interact with the Lock object declared above
   task type Worker is
      entry Start (Sleep : in Duration; Id : in Positive);
   end Worker;

   task body Worker is
      Sleep_Time : Duration;
      My_Id : Positive;
   begin
      accept Start(Sleep : in Duration; Id : in Positive) do
         My_Id := Id;
         Sleep_Time := Sleep;
      end Start;
      --Acquire the lock. The task will suspend until the Acquire call completes
      Lock.Acquire;
      Put_Line("Task #" & Positive'Image(My_Id) & " acquired the lock.");
      -- Suspend the task for Sleep_Time seconds
      delay Sleep_Time;
      -- Release the lock. Release is unconditional and happens without suspension
      Lock.Release;
   end Worker;

   -- Create an array of 5 Workers
   type Staff is array(Positive range 1..5) of Worker;
   Crew : Staff;
begin
   for I in Crew'range loop
      Crew(I).Start(2.0, I);
   end loop;
end Semaphores_Main;

E

This semaphore slightly differs from the task description; the release operation is not on the semaphore itself but given out with each acquisition, and cannot be invoked too many times.

def makeSemaphore(maximum :(int > 0)) {
    var current := 0
    def waiters := <elib:vat.makeQueue>()
    def notify() {
        while (current < maximum && waiters.hasMoreElements()) {
            current += 1
            waiters.optDequeue().resolve(def released)
            when (released) -> {
                current -= 1
                notify()
            }
        }
    }
    def semaphore {
        to acquire() {
            waiters.enqueue(def response)
            notify()
            return response
        }
        to count() { return current }
    }
    return semaphore
}

def work(label, interval, semaphore, timer, println) {
    when (def releaser := semaphore <- acquire()) -> {
        println(`$label: I have acquired the lock.`)
        releaser.resolve(
            timer.whenPast(timer.now() + interval, fn {
                println(`$label: I will have released the lock.`)
            })
        )
    }
}

def semaphore := makeSemaphore(3)
for i in 1..5 {
    work(i, 2000, semaphore, timer, println)
}

Java

public class CountingSemaphore
{
   private int lockCount = 0;
   private int maxCount;

   CountingSemaphore(int Max)
   {
      maxCount = Max;
   }
  
   public synchronized void acquire() throws InterruptedException
   {
      while( lockCount >= maxCount)
      {
         wait();
      }
      lockCount++;
   }
   public synchronized void release()
   {
      if (lockCount > 0)
      {
         lockCount--;
         notifyAll();
      }
   }
   public synchronized int getCount()
   {
      return lockCount;
   }
}
public class Worker extends Thread
{
   private CountingSemaphore lock;
   private int id;

   Worker(CountingSemaphore coordinator, int num)
   {
      lock = coordinator;
      id = num;
   }
   Worker()
   {
   }
   public void run()
   {
      try
      {
         lock.acquire();
         System.out.println("Worker " + id + " has acquired the lock.");
         sleep(2000);
      }
      catch (InterruptedException e)
      {
      }
      finally
      {
         lock.release();
      }
   }
   public static void main(String[] args)
   {
      CountingSemaphore lock = new CountingSemaphore(3);
      Worker crew[];
      crew = new Worker[5];
      for (int i = 0; i < 5; i++)
      {
         crew[i] = new Worker(lock, i);
         crew[i].start();
      }

   }
}

Perl

See Coro::Semaphore.